这是我在 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
那么,为什么即使在输出中我将 o 转换回 Object 类,该语句仍输出 true?甚至
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。当运行 cast 函数时,实际上应该发生的是
类似于 return (Object) i;
的内容。
正如我上面的第一个问题,为什么 System.out.println(o instanceof String);
打印 true? o 不应该是 Object 类型吗?
期待您的回答,谢谢:)!
最佳答案
So why does this statement print true even though inside the print I cast o back to an Object class?
您只是将引用转换为 Object
。实际对象仍然是String
类型的对象。并且 instanceof
检查是针对实际实例,而不是引用类型。
prints that o is of class String. Why so?
getClass()
方法返回运行时对象类型的 Class
实例。
why does System.out.println(o instanceof String); print true?
正如您所注意到的,您正在将一个 String
类型作为参数传递给您的 cast()
方法。因此,即使引用类型是 Object
,实际对象也是 String
类型。由于泛型,这里没有什么特别的事情发生。道理是一样的,结果也是一样的。
关于java - 多态性、转换为对象和类型删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29679226/