在java中是否可以获取对象的完整层次结构? 我已经检查了 Class 类的 javadoc,但找不到这样的方法。 另外,我觉得奇怪的是以下代码的结果:
public static void main(String[] args) throws ClassNotFoundException {
ClassLoader loader = ClassLoaderTest.class.getClassLoader();
Class<?> clazz = loader.loadClass("java.lang.Integer");
System.out.println(clazz.getSuperclass()); //prints java.lang.Number
System.out.println(clazz.isInstance(clazz.getSuperclass())); //returns false??
Number number = new Integer(1);//no class cast exception
}
isInstance() 方法的文档说:
Determines if the specified {@code Object} is assignment-compatible * with the object represented by this {@code Class}.
既然我们可以将 Integer 赋值给 Number,为什么会这样呢:
java.lang.Integer.class.isInstance(java.lang.Number.class);
返回错误?
谢谢
最佳答案
重新引用 javadoc
Determines if the specified
Object
is assignment-compatible * with the object represented by thisClass
.
在表达式中
java.lang.Integer.class.isInstance(java.lang.Number.class);
您正在检查表达式 java.lang.Number.class
返回的对象是否为是 Integer
的一个实例。 不是,它是 java.lang.Class
的一个实例.
它应该像这样使用
java.lang.Integer.class.isInstance(new Integer(1)); // if you want it to return true
你可以传递任何你想要的东西,但它只会返回 true
如果使用的参数是 Integer
或其子类型之一(但它是 final
所以没有)。
Integer
是 Number
的子类型.
任何 Integer
可以在 Number
的情况下使用实例需要对象。
关于java - 关于 Class.isInstance 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21991524/