关于反射包的问题
我从sun网站上读到,对于每个引用jvm都创建一个不可变的类对象 以便它可以内省每个类的运行时信息。 sun 提到使用 .class 语法。我想知道这个语法的内部机制以及它是如何工作的。
I read from sun website that for every reference jvm is creating one immutable class object
so that it can introspect the run time information of every class. And sun has mentioned to use .class syntax. I want to know the internal mechanism of this syntax and how it works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能需要从反射教程开始
.class
语法解释在此页面(不,它没有不解释内部工作原理)You may want to start with the reflection tutorial
The
.class
syntax is explained on this page (no, it doesn't explain the inner workings)如果使用
-target 1.4
或更早版本编译,则调用一次Class.forName(String)
,然后将Class
引用存储在合成静态字段中调用类。对于-target 1.5
及更高版本,新版本的ldc
(“加载常量”)字节码操作引用该类。使用
javap -c
查看javac 生成的字节码。If compiled with
-target 1.4
or earlier,Class.forName(String)
is called once and thenClass
reference stored in a synthetic static field in the calling class. For-target 1.5
and later, a new version of theldc
("load constant") bytecode operation references the class.Use
javap -c
to see the bytecode that javac produces.对于每个非泛型(或原始)类型(类、接口、数组类型、原始类型),都有一个 Class 对象,在加载此类时创建。该对象并非完全不可变,因为它包含类的静态变量。
如果你有一个对象,你可以通过调用
o.getClass()
来获取其实现类的类对象。如果你有某种类型,你可以通过Java中的T.class
来获取它的类对象。从类对象中,您可以检查您的类,获取构造函数、方法、字段、超类、实现的接口等 - 这称为反射。
(有关更多详细信息,请参阅其他答案中的链接。)
For each non-generic (or raw) type (Class, interface, array-type, primitive type) there is a Class object, created when this class is loaded. This object is not totally immutable, as it contains the static variables of the class, for example.
If you have an object, you can get the class object of its implementing class by calling
o.getClass()
. If you have some type, you can get its class object byT.class
in Java.From the class object you can inspect your class, to get constructors, methods, fields, superclass, implemented interfaces, and so on - this is called reflection.
(See the links in the other answers for more details.)