What is a class literal in Java?

2019-01-01 15:45发布

From the Java tutorial:

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.

To what type of variable can this literal be assigned to?

Please give a small example if possible.

标签: java literals
9条回答
弹指情弦暗扣
2楼-- · 2019-01-01 15:48

The literal itself is MyClass. If you write MyClass.class you get a Reference to the class object. If you write new MyClass(), it uses the literal to get you an instance of the class object you get by MyClass.class. From the instance you get the same class object by calling myClassInstance.getClass().

I am not 100% sure, but the literal itself cannot be assigned to any variable. What you can do is getting the name of the class as string and use the reflection framework to create an instance.

查看更多
忆尘夕之涩
3楼-- · 2019-01-01 15:51

Thanks to the other good answers here, you know what it is, but here's a typical usage example that may clarify also:

    private static Logger log = Logger.getLogger(YourClassHere.class);

As the code suggests, this is a line where we're initialising a logging framework (in this example, I'm using the org.apache.log4j package, but the principle extends to other frameworks). The getLogger() method requires a class literal so it knows what it's logging (i.e. the current object's class).

查看更多
冷夜・残月
4楼-- · 2019-01-01 15:57

When the JVM loads your application classes, it stores them as java.class.Class objects.

So, there are usually several instances of type Class in memory that represents your classes. So you can do something like this:

Class<Bicycle> bicycleClass = Bicycle.class; // returns the object storing your Bicycle class
bicycleClass.getName();  // returns your class name
bicycleClass.getDeclaredMethods();  // returns your (declared) class methods
查看更多
临风纵饮
5楼-- · 2019-01-01 15:59

According to the JLS

15.8.2 Class Literals

A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a . and the token class. The type of a class literal is Class. It evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.

查看更多
深知你不懂我心
6楼-- · 2019-01-01 16:01

Some common uses may be found in Class Literals as Runtime-Type Tokens.

查看更多
无与为乐者.
7楼-- · 2019-01-01 16:04
Class<String> c = String.class;

Check out the Javadoc for java.lang.Class to see what you can do with one of these little guys - mostly related to reflection

查看更多
登录 后发表回答