为什么“t instanceof T”在T是类型参数且t是变量的情况下不允许? [英] Why "t instanceof T" is not allowed where T is a type parameter and t is a variable?

查看:1072
本文介绍了为什么“t instanceof T”在T是类型参数且t是变量的情况下不允许?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我同意,在运行时,没有类型信息保留。但考虑以下类的通用声明:

  class SomeClass< T> {
T t;
SomeClass(Object o){
System.out.println(o instanceof T); //非法
}
}

在运行时,不会存在T !但是,如果我实例化这类Integer类,那么相应的对象将有一个Integer类型的字段t。

然后,为什么我不能检查一个类型的a T可以用Integer在运行时替换。实际上我会做类似o instanceof Integer。



在这种情况下,允许instanceof使用类型参数会导致麻烦,但是如果我实例化这类Integer类,那么
对应的对象将会有一个Integer类型的字段t

不,它不会。它将有一个Object类型的字段。

请考虑以下代码:

  SomeClass的<整数> c = new SomeClass< Integer>(); 
SomeClass untyped =(SomeClass)c; //是哪种类型?
SomeClass< String> stringTyped =(SomeClass< String>)无类型; //现在它是STRING?

作品。给你一堆编译器警告,但工作。因为字段T实际上是Object类型,可以转换为任何东西。


Eclipse says that the instanceof operation is not allowed with Type Parameter due to generic type eraser.

I agree that at runtime, no type information stays. But consider the following generic declaration of class :

class SomeClass<T>{
    T t;
    SomeClass(Object o){
        System.out.println(o instanceof T);   // Illegal
    }   
}        

At runtime, no T would be present! But if I instantiate this class of type Integer, then the corresponding object will have a field t of type Integer.

Then, why can't I check the type of a variable with T which can be replaced by Integer at runtime. And I would be actually doing something like "o instanceof Integer".

Under which cases, allowing instanceof with a Type Parameter can cause trouble so that it is prohibited?

解决方案

But if I instantiate this class of type Integer, then the corresponding object will have a field t of type Integer

No, it won't. It will have a field of type Object. Just everytime you access it, it will be cast to an Integer.

Consider the following code:

SomeClass<Integer> c = new SomeClass<Integer>();
SomeClass untyped = (SomeClass)c; // Which type was it?
SomeClass<String> stringTyped = (SomeClass<String>)untyped; // Now it's STRING??

Works. Gives you a bunch of compiler warnings, but works. Because the field T is actually of type Object and can be cast to anything.

这篇关于为什么“t instanceof T”在T是类型参数且t是变量的情况下不允许?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆