java 为什么 String 的 format(Object... args) 被定义为静态方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/792259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is String's format(Object... args) defined as a static method?
提问by Randy Sugianto 'Yuku'
I wonder why Java5 and above provide a printf-style formatter using a static method in class String like this:
我想知道为什么Java5 及更高版本使用 String 类中的静态方法提供 printf 样式的格式化程序,如下所示:
public static String format(String format, Object... args)
instead of
代替
public String format(Object... args)
so that we can write "%02d".format(5)to get 05instead of String.format("%02d", 5).
这样我们就可以写成"%02d".format(5)get05而不是String.format("%02d", 5).
I imagined if I could modify the String class, I could add this:
我想如果我可以修改 String 类,我可以添加这个:
public String format(Object... args) {
return format(this, args)
}
to get the same result.
得到相同的结果。
I found that in C#, a static method is also used instead of an instance method.
我发现在 C# 中,还使用了静态方法而不是实例方法。
I wonder why they decided to do this, but I didn't come to an explanation. The instance methods trimand substringreturns a new instance of string, so they should have done the same thing with format.
我想知道他们为什么决定这样做,但我没有做出解释。实例方法trim并substring返回字符串的新实例,因此它们应该对format.
Moreover, the DateFormatclass also uses this:
此外,DateFormat该类还使用了这个:
public final String format(Date date)
for formatting dates. So if we consider the instance of DateFormat as the formatter, an instance of String could also be used as a formatter.
用于格式化日期。因此,如果我们将 DateFormat 的实例视为格式化程序,则 String 的实例也可以用作格式化程序。
Any ideas?
有任何想法吗?
采纳答案by coobird
Perhaps "%02d".format(5)seems to imply that the object on which the formatmethod is being called is a format string.
也许"%02d".format(5)似乎暗示format调用该方法的对象是格式字符串。
In this case, the format string happens to also be a String, so furthering that point, one could argue that all Strings are format strings.
在这种情况下,格式字符串恰好也是 a String,因此进一步说明这一点,人们可能会争辩说所有Strings 都是格式字符串。
Probably this can be avoided by saying that a static method in the Stringclass can be used to format a string, rather than making some implicit statement about all Strings in general.
可能这可以通过说类中的静态方法String可用于格式化字符串来避免,而不是对所有Strings进行一些隐式声明。
回答by Brandon Yarbrough
While I am not a designer of Java, I can tell you one clear reason for making it static.
虽然我不是 Java 的设计者,但我可以告诉您将其设为静态的一个明确原因。
Java 5 came out with many features, but two of note were:
Java 5 推出了许多功能,但有两个值得注意的是:
- The ability to perform "import static" commands that allowed static methods to be used from within a class easily and without listing their class name.
- A static utility method that performed printfs easily.
- 能够执行“导入静态”命令,允许在类中轻松使用静态方法,而无需列出它们的类名。
- 一种静态实用方法,可以轻松执行 printfs。
While it'd be nice to be able to say "bla: %d".format("foo"),by making the method static you can use format in a way that's very familiar and clean-looking to C programmers used to printf().
虽然很高兴能够"bla: %d".format("foo"),通过将方法设为静态来表示您可以以一种对过去的 C 程序员来说非常熟悉和干净的方式使用格式printf()。
import static java.lang.String.format;
public class Demo {
public void Test() {
//Do some stuff
format("Hey, this is easy to read!");
}
}
And that's why! By using static imports, printfs look almost exactly like they do in C. Awesome!
这就是为什么!通过使用静态导入,printfs 看起来几乎与它们在 C 中所做的完全一样。太棒了!
回答by Uri
The main reason is probably that the designers of Java did not want to add too much stuff to the interface of String. Making it a member function would have meant putting it on string. Remember that a non-static method would have to be on the String object.
主要原因可能是Java的设计者不想在String的接口中添加太多的东西。使它成为成员函数意味着将它放在字符串上。请记住,非静态方法必须位于 String 对象上。
A second reason is that the static format maintains its resemblance to C's printf, which looks like printf(FORMAT, ARG1, ARG2...)
第二个原因是静态格式与 C 的 printf 保持相似,它看起来像 printf(FORMAT, ARG1, ARG2...)
Another reason is that format is overloaded: there is a version that takes locale as the first parameter (before the string), so doing this on the string object would be tricky.
另一个原因是格式过载:有一个版本将语言环境作为第一个参数(在字符串之前),因此在字符串对象上执行此操作会很棘手。
回答by ggf31416
"%02d".format(5) would look like "%02d" is formatted using the format 5 rather than the opposite. Also most strings are not suitable as format ("hello world".format(5)?), so the method should throw exceptions for most string objects.
"%02d".format(5) 看起来像 "%02d" 使用格式 5 而不是相反的格式。此外,大多数字符串不适合作为格式(“hello world”.format(5)?),因此该方法应该为大多数字符串对象抛出异常。
回答by isntn
Answer rests in responsibility of Format method.
答案由 Format 方法负责。
It is more logical and intuitive, at least to me, to say that "format string is input to Format method" than to say that "Format operates on format string". This is so, as we "usually" pass format string, known at design time, to Format. In contrast, for Trim, we "usually" pass variable string whose value is not known at design time.
至少对我而言,说“格式字符串输入到 Format 方法”比说“格式对格式字符串进行操作”更合乎逻辑和直观。之所以如此,是因为我们“通常”将设计时已知的格式字符串传递给 Format。相比之下,对于 Trim,我们“通常”传递其值在设计时未知的变量字符串。
So, making format method static, make code reading more intuitive. Look at following (C#).
所以,让格式化方法静态化,让代码阅读更直观。看下面(C#)。
answer = String.Format("This is format string : {0}", someValue);
//More readable to me
answer = "This is format string : {0}".Format(someValue);
EDIT: Even though I have used C# example code, it applies well to Java. I got -ve vote for using C# syntax!
编辑:即使我使用了 C# 示例代码,它也适用于 Java。我得到了 -ve 使用 C# 语法的投票!
回答by Vitja
I really think formatmust be an instance method of String and so also do
我真的认为format必须是 String 的实例方法等等
- python:
2.6: print "%s" % ("Hello")3.0: print("{0}".format("Hello")) - scala:
2.7.6: println("%s".format("Hello"))
- Python:
2.6: print "%s" % ("Hello")3.0: print("{0}".format("Hello")) - 斯卡拉:
2.7.6: println("%s".format("Hello"))
回答by Hyman Dsilva
answer = String.Format("This is format string : {0}", someValue);
//More readable to me
answer = "This is format string : {0}".Format(someValue);
回答by Jian Chen
Just bad design. A pythoner finds it painful.
只是糟糕的设计。蟒蛇发现它很痛苦。
回答by Peter Lawrey
Calling strfmt.format(objects) instead of String.format(strfmt, objects)
调用 strfmt.format(objects) 而不是 String.format(strfmt, objects)
- is an Object Orientated call instead of a call to a static helper.
- its shorter to type.
- its simpler as it has one less argument.
- its easier to use with code completion. If you start with the format string and hit . you get the format() as an option in an IDE.
- String.format(strfmt, objects) could be accidental called as strfmt.format(text, objects) which wouldn't do what it appears to do.
- 是面向对象的调用,而不是对静态助手的调用。
- 它的输入更短。
- 它更简单,因为它少了一个论点。
- 它更容易与代码完成一起使用。如果您从格式字符串开始并点击 . 您将 format() 作为 IDE 中的一个选项。
- String.format(strfmt, objects) 可能会被意外称为 strfmt.format(text, objects) ,它不会做它看起来做的事情。
回答by dlamblin
Merely because the call is reminiscent of C's sprintffunction.
仅仅是因为这个调用让人想起 C 的sprintf函数。

