gpt4 book ai didi

java - 类文字在静态方法中究竟是如何求值的?

转载 作者:行者123 更新时间:2023-11-30 06:17:53 25 4
gpt4 key购买 nike

来自 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)构造函数。相反,类对象由 Java 虚拟机在加载类时自动构建,并通过调用类加载器中的 defineClass 方法来构建。

以下示例使用 Class 对象打印对象的类名:

 void printClassName(Object obj) {
System.out.println("The class of " + obj +
" is " + obj.getClass().getName());
}

也可以使用类字面量获取命名类型(或 void)的 Class 对象。请参阅 The Java™ Language Specification 的第 15.8.2 节。例如:

System.out.println("The name of class Foo is: "+Foo.class.getName());

关于java - 类文字在静态方法中究竟是如何求值的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25454460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com