来自 JLS (§15.8.2):
A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader (§12.2) of the class of the current instance.
这是有道理的,但是如果没有“当前实例”怎么办? (即表达式位于类方法中,也称为“静态方法”)
我的直觉告诉我使用相同的规则,将“当前实例的类”替换为“类方法的类”之类的内容。然而,我在 JLS 中找不到任何此类规则,根据我的经验,该规则往往非常明确。这让我不确定自己的直觉。
另一种情况是,我的假设是在类方法中没有“当前实例”,这是不正确的。如果是这样 - 在类方法中确定“当前实例”的规则是什么?
最佳答案
当前实例的类表示类型为T的java.lang.Class的实例。即使所考虑的类有静态方法,它也始终是一个java.lang.Class 的实例。
java.lang.Class的Java文档可以得到相关解释:
Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
类没有公共(public)构造函数。相反,Class 对象是由 Java 虚拟机在加载类时通过调用类加载器中的 DefineClass 方法自动构造的。
以下示例使用 Class 对象来打印对象的类名:
void printClassName(Object obj) {
System.out.println("The class of " + obj +
" is " + obj.getClass().getName());
}
还可以使用类文字获取命名类型(或 void)的 Class 对象。请参阅《Java™ 语言规范》第 15.8.2 节。例如:
System.out.println("The name of class Foo is: "+Foo.class.getName());
关于java - 类文字在静态方法中究竟是如何计算的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25454460/