gpt4 book ai didi

java - java 通用层次结构中的运行时类型比较

转载 作者:行者123 更新时间:2023-12-01 18:13:21 25 4
gpt4 key购买 nike

我无法理解完整引用中的这段文字代码是这样的,

public class Generic
{
public static void main(String[] args)
{
SuperClass<Integer> s1=new SuperClass<>(135);
SubClass<Double> s2=new SubClass<>(1.35);
if(s1 instanceof SuperClass<Integer>)
{
System.out.println("I am instance of SuperClass");
}
}
}

class SuperClass<T>
{
T y;
SuperClass(T ob)
{
y=ob;
}
T ret()
{
return(y);
}
}

class SubClass<T> extends SuperClass<T>
{
T x;
SubClass(T y)
{
super(y);
x=y;
}
}

根据正文,

if(s1 instanceof SuperClass<Integer>) this line can’t be compiled because it attempts to compare s1 with a specific type of SuperClass,in this case, SuperClass<Integer>. Remember, there is no generic type information available at run time. Therefore, there is no way for instanceof to know if s1 is an instance of SuperClass<Integer> or not.

有人可以解释一下这些行到底是什么意思吗?

最佳答案

当您的 .java 文件被编译为 .class 文件(也称为字节码)时,SuperClass<Integer>这段代码被转换为 SuperClass 。这称为类型删除。所以在运行时没有关于泛型类型的信息。

关于java - java 通用层次结构中的运行时类型比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31233866/

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