ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

在Java中,此类类将编译为什么?

2019-10-28 05:00:11  阅读:174  来源: 互联网

标签:reflection java compilation


下面是定义类类型的代码:

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中引用该常量时加载了该常量.

标签:reflection,java,compilation
来源: https://codeday.me/bug/20191028/1950113.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有