这是我在Stackoverflow上的第一个问题,我希望你能帮助我解决我现在遇到的理解问题。
让我们说我这样做:
Object o = null;
String s = "Test";
System.out.println(o instanceof String); //This returns false
o = s;
System.out.println(o instanceof String); //This returns true
到目前为止一切顺利,但现在我做的时候:
System.out.println( ((Object) o) instance of String) //Still prints true
那么为什么这个语句打印为真,即使在我打印回到Object类的内容中?甚至
System.out.println(((Object)o).getClass())
打印出o是String类。为什么这样?
这导致我的第二个问题与泛型和类型擦除有关。 我查看了这样的代码示例:
private static <T> T cast(Object i){
return (T) i;
}
public static void main(String[] args){
Object o = null;
try{
o = main.<Double> cast("Test");
}catch(ClassCastException ex) {
System.out.println("Could not cast properly");
}
System.out.println(o == null); //Prints false
System.out.println(o instanceof String); //Prints true
System.out.println(o instanceof Double); //Prints false
}
根据我对类型擦除的理解,所有泛型T将在运行时被Object替换。在运行强制转换函数时,实际应该发生什么
return (Object) i;
的某些内容。
作为我上面的第一个问题,为什么System.out.println(o instanceof String);
打印为真?不应该是对象类型吗?
期待您的回答,谢谢:)!
答案 0 :(得分:1)
那么为什么这个语句打印为真,即使在我打印回到Object类的内容中?
您只是将引用转换为Object
。实际对象仍然是String
类型的对象。并且instanceof
检查是针对实际实例的,而不是引用类型。
打印出o是String类。为什么这样?
getClass()
方法返回运行时对象类型的Class
实例。
为什么System.out.println(o instanceof String);打印真的吗?
如您所知,您已将String
类型作为参数传递给cast()
方法。因此,即使引用类型为Object
,实际对象也是String
类型。由于泛型,这里没有什么特别之处。推理是一样的,结果也一样。