下面是定义类类型的代码:
package annotationtype;
public class Example {
public static void main(String[] args){
}
}
由javac从功能上编译为:
public class annotationtype.Example{
public static Class<annotationtype.Example> class;
{
class = Class.forName("annotationtype.Example")
}
public annotationtype.Example(){}
public static void main(java.lang.String[] args){}
}
我的主要重点是Class< annotationtype.Example>上面的代码中的类静态成员变量.另外,该成员变量Class<注释类型.实际上,class指向的是Class类类型的对象,该类在将Example实例加载到内存后维护了Example类的元数据. 我的理解正确吗?
解决方法:
类文字是语言规范的一部分,如JLS 15.8.2中所述
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a ‘.’ and the token class.
The type of C.class, where C is the name of a class, interface, or
array type (§4.3), is Class<C>.The type of p.class, where p is the name of a primitive type (§4.2),
is Class<B>, where B is the type of an expression of type p after
boxing conversion (§5.1.7).The type of void.class (§8.4.5) is Class<Void>.
javac不会为每个类创建一个静态类字段,但是它将识别一个类文字表达式并正确地对其进行编译.
以班级为例:
public class Hello {
public static void main(String[] args){
Class<?> myClass = Hello.class;
System.out.println("Hello, " + myClass);
}
}
编译为(仅包括字节码的相关部分):
public class Hello minor version: 0 major version: 52 flags:
ACC_PUBLIC, ACC_SUPER
Constant pool:
#1 = Methodref #11.#20 // java/lang/Object."<init>":()V
#2 = Class #21 // Hello
......
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=3, locals=2, args_size=1
0: ldc #2 // class Hello
2: astore_1
您可以看到javac在常量池中放置了对Hello类的引用,然后在main中引用该常量时加载了该常量.