是否可以编写一个打印语句本身的 Java printf 语句?
是否可以有一个 Java printf
语句,其输出就是语句本身?
一些片段来说明:
// attempt #1
public class Main {
public static void main(String[] args) {
System.out.printf("something");
}
}
这会打印something
。
因此,尝试 #1 的输出与尝试 #1 中的 printf
语句并不完全相同。我们可以尝试这样的事情:
// attempt #2
public class Main {
public static void main(String[] args) {
System.out.printf("System.out.printf(\"something\");");
}
}
现在输出是 System.out.printf("something");
所以现在尝试 #2 的输出与输出 #1 中的语句匹配,但是我们回到我们之前遇到的问题,因为我们需要尝试 #2 的输出来匹配尝试 #2 中的语句。
那么是否可以编写一行 printf 语句来打印自身呢?
Is it possible to have a Java printf
statement, whose output is the statement itself?
Some snippet to illustrate:
// attempt #1
public class Main {
public static void main(String[] args) {
System.out.printf("something");
}
}
This prints something
.
So the output of attempt #1 is not quite exactly the printf
statement in attempt #1. We can try something like this:
// attempt #2
public class Main {
public static void main(String[] args) {
System.out.printf("System.out.printf(\"something\");");
}
}
And now the output is System.out.printf("something");
So now the output of attempt #2 matches the statement in output #1, but we're back to the problem we had before, since we need the output of attempt #2 to match the statement in attempt #2.
So is it possible to write a one-line printf
statement that prints itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这并不漂亮,但这当然是可能的:
输出(在 ideone.com 上运行)是:
此输出与
printf
语句匹配。可能有更短的解决方案。
另请参阅
java.util.Formatter语法
%[argument_index$]转化
It's not pretty, but this is certainly possible:
The output (as run on ideone.com) is:
This output matches the
printf
statement.There are likely to be shorter solutions.
See also
java.util.Formatter
syntax%[argument_index$]conversion
System.out 是一个静态 PrintStream 实例,可以通过 inovking System.out.setOut(PrintStream s) 替换为任何 PrintStream。
因此,只需编写 PrintStream 的子类并重写必要的方法即可。
下面只是一个非常简单的例子来进行演示。建议重写更多方法。
现在我们测试上面的类:
System.out is a static PrintStream instance which may be replaced with any PrintStream by inovking System.out.setOut(PrintStream s).
So, just write a subclass of PrintStream and override the necessary methods.
The following is just a very simple example for demonstration. It's advisable to override more methods.
Now we test the above class: