这里方法“returnObj”如何能够返回“TestGen”类型的对象,即使“类型删除”已将 T 减少为对象。
class TestGen
{
}
class MyGeneric<T>
{
T obj;
MyGeneric(T giveObj)
{
obj = giveObj;
}
T returnObj()
{
return obj;
}
}
public class TestGeneric {
public static void main(String[] args) {
MyGeneric<TestGen> mg = new MyGeneric<TestGen>(new TestGen());
TestGen tg = mg.returnObj();
}
}
最佳答案
这都是编译器的诡计:因为编译器知道MyGeneric
的类型参数是TestGen
,所以它悄悄地在幕后插入一个类型转换。如果你从字节码反编译回调,它看起来像这样:
TestGen tg = (TestGen)mg.returnObj();
编译器已验证调用将在运行时成功。
关于java - 即使类型删除已将 T 减少为对象,如何返回对象的确切类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093841/