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 16:07

In examples it is someting like that:

Class myClass = MyClass.class

or

MyClass.class.getResourceAsStream("config.properties");
查看更多
人间绝色
3楼-- · 2019-01-01 16:10

To understand that, you have to understand that String is an instance (object) of its superclass (parent class) Object.

class String's instance (object)'s value is a String literal (e.g. "I am a string.") :

class   |  instance (object) |  literal
------------------------------------------------
String  |  instance_name  =  |  "I am a string."

whereas class Object's instance (object)'s value is a Class literal — (e.g. Hashtable.class) which refers to class Hashtable's instance (object)

class      |  instance (object) |  literal
------------------------------------------------
Hashtable  |  instance_name     |  Hashtable.
查看更多
唯独是你
4楼-- · 2019-01-01 16:12

To understand that, you have to understand that String is an instance (object) of the class Class. A string literal (e.g. "I am a string.") is a notation which represents an instance (object) of the class String, whereas a class literal (e.g. Hashtable.class) is a notation which represents an instance of the class Class.

查看更多
登录 后发表回答