什么是类对象(java.lang.Class)?
Class
对象在类加载时由 Java 虚拟机自动构造,并通过调用类加载器中的 defineClass
方法.
Class
objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to thedefineClass
method in the class loader.
这些 Class
对象是什么?它们与通过调用 new
从类实例化的对象相同吗?
What are these Class
objects? Are they the same as objects instantiated from a class by calling new
?
另外,例如 object.getClass().getName()
如何将所有内容都类型转换为超类 Class
,即使我没有从 继承java.lang.Class
?
Also, for example object.getClass().getName()
how can everything be typecasted to superclass Class
, even if I don't inherit from java.lang.Class
?
Class
没有任何内容.Java 中的每个Object
都属于某个class
.这就是为什么所有其他类都继承的 Object
类定义了 getClass()
方法.
Nothing gets typecasted to Class
. Every Object
in Java belongs to a certain class
. That's why the Object
class, which is inherited by all other classes, defines the getClass()
method.
getClass()
或类字面量 - Foo.class
返回一个 Class
对象,其中包含有关该类的一些元数据:
getClass()
, or the class-literal - Foo.class
return a Class
object, which contains some metadata about the class:
- 姓名
- 包装
- 方法
- 字段
- 构造函数
- 注释
以及一些有用的方法,如转换和各种检查(isAbstract()
、isPrimitive()
等).javadoc 准确显示了您可以获得哪些信息关于一堂课.
and some useful methods like casting and various checks (isAbstract()
, isPrimitive()
, etc). the javadoc shows exactly what information you can obtain about a class.
因此,例如,如果您的方法被赋予一个对象,并且您希望处理它,以防它使用 @Processable
批注进行批注,则:
So, for example, if a method of yours is given an object, and you want to process it in case it is annotated with the @Processable
annotation, then:
public void process(Object obj) {
if (obj.getClass().isAnnotationPresent(Processable.class)) {
// process somehow;
}
}
在此示例中,您获取有关给定对象的类(无论它是什么)的元数据,并检查它是否具有给定的注释.Class
实例上的许多方法称为反射操作",或简称为反射.阅读此处,了解反射、使用原因和使用时间.
In this example, you obtain the metadata about the class of the given object (whatever it is), and check if it has a given annotation. Many of the methods on a Class
instance are called "reflective operations", or simply "reflection. Read here about reflection, why and when it is used.
另请注意,Class
对象表示正在运行的 Java 应用程序中的枚举和接口以及类,并具有相应的元数据.
Note also that Class
object represents enums and intefaces along with classes in a running Java application, and have the respective metadata.
总结——java中的每个对象都有(属于)一个类,并且有一个各自的Class
对象,其中包含关于它的元数据,可以在运行时访问.
To summarize - each object in java has (belongs to) a class, and has a respective Class
object, which contains metadata about it, that is accessible at runtime.