Was the class literal syntax necessary?
I know well, what is a class literal in java, I just wonder, wha开发者_运维技巧t is the reason for the .class
in the syntax. Is there any ambiguity removed by this? I mean, wouldn't an alternative Java syntax using
Class<String> c = String;
instead of
Class<String> c = String.class;
work? To me the class
keyword looks like a boilerplate.
Sure, you could make that the syntax. But using the .class
suffix makes the compiler's job easier; it has to do less work to know that the code is syntactically correct.
Without the suffix, the compiler would have to work harder to understand the difference between this:
String.getName() // a method inherited from java.lang.Class<T>
and this:
String.valueOf(...) // a static method from java.lang.String
If you don't think that the .class
suffix is needed, do you also think that the f
and L
suffices are useless (for float
and long
literals, respectively)?
It's just not the same thing. String
is a class of type string, and String.member
is one of its member variables, String.method()
would be one of its methods.
String.class
is an object of type Class
that defines String
. It seems a lot more intuitive that you need to specify .class
to indicate that you're trying to refer to an object of type Class
.
Not to mention that it's easier to parse this kind of construct, and potentially prevents bugs where you're accidentally returning a Class
object when you didn't mean to.
This is even more relevant when you're looking at inner classes, like OuterClass.InnerClass.class
.
To work with Matt's example: How would you work on the class object without having to create a temporary variable first? Assuming your class Foo
has a static method called getClasses
, how would you differentiate between Foo.getClasses
and Foo.class.getClasses
?
String
is the String class pseudo-object which provides access to the classes static fields and methods, including class
, which refers to the Class
instance which describes the String class. So they are distinct, but because Java doesn't have the metaclass arrangement of (say) Smalltalk-80 this isn't very clear.
You could certainly make String
and String.class
synonymous if you wanted to, but I think there is a valid basis for the distinction.
Let's use integer as an example:
Class<Integer> c = Integer; // your proposal
int i = Integer.MAX_VALUE; // compare with below
int j = c.MAX_VALUE; // hmm, not a big fan, personally
It just doesn't seem to flow, in my opinion. But that's just my opinion :)
精彩评论