Class java.lang.Class 具有私有字段 name 。我正在尝试为不同的Class实例获取此字段的值,但是当涉及到 Integer.class 时,返回的值为null。这是代码示例:
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws Throwable {
Class<Object> objectCls = Object.class;
Class<Integer> integerCls = Integer.class;
Class<Class> classCls = Class.class;
Field nameField = classCls.getDeclaredField("name");
nameField.setAccessible(true);
System.out.println(nameField.get(objectCls));
System.out.println(nameField.get(integerCls));
System.out.println(nameField.get(classCls));
}
}
输出将是:
java.lang.Object
null
java.lang.Class
我也尝试使用使用JDK 9和10的在线编译器执行,在那里很好。所以问题是当我使用JDK 8执行此代码时。
答案 0 :(得分:0)
instead of using private field through reflection You can just use integerCls.getName()
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws Throwable {
Class<Object> objectCls = Object.class;
Class<Integer> integerCls = Integer.class;
Class<Class> classCls = Class.class;
Field nameField = classCls.getDeclaredField("name");
nameField.setAccessible(true);
System.out.println(nameField.get(objectCls));
/*System.out.println(nameField.get(integerCls));*/
System.out.println(integerCls.getName());
System.out.println(nameField.get(classCls));
} }