Question

in the Java tutorial http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html , class literals is mentioned as a "literal type"

Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.

but in the Java Specification http://docs.oracle.com/javase/specs/jls/se7/html/ , class literals is not put under the 3.10 Literals type, but instead is put under 15.8. Primary Expressions

So why is that?

Was it helpful?

Solution

what exactly is the type of class literal in Java?

The erased type is java.lang.Class.

The non-erased type of Foo.class would be java.lang.Class<Foo>.


The reason it is in the JLS as a primary expression is technical:

  • A class literal is not a unitary literal. It is three (or more) distinct symbols that combine to form this "constanty, literally sort of thing".

  • They decided to call it a literal because the value is a constant.

  • From a syntactic point of view it has to go into the same part of the grammar as the (other) primary expressions ... in order for the grammar to describe the language without a mass of ambiguity / context sensitivity.

So it really could go in either place in the JLS. But they have to put it in only one place. And since the other literals in the Literal section are unitary (i.e. one symbol), it makes sense to put it into the Primary Expression section.

But the bottom line is that it doesn't really matter why they decided to organize the JLS that way. The meaning of a class literal does not depend in where it is specified.

OTHER TIPS

Don't take the name too literally. A Foo.class is equivalent to Class.forName("pkg.Foo"), which is far more complicated than simple literals like 1 and "abc".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top