加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么“t instanceof T”不允许,其中T是类型参数,t是变

发布时间:2020-12-14 23:48:27 所属栏目:Java 来源:网络整理
导读:Eclipse表示,由于泛型橡皮擦,Type Parameter不允许使用instanceof操作. 我同意在运行时,不会保留类型信息.但请考虑以下类的通用声明: class SomeClassT{ T t; SomeClass(Object o){ System.out.println(o instanceof T); // Illegal } } 在运行时,不会出现T
Eclipse表示,由于泛型橡皮擦,Type Parameter不允许使用instanceof操作.

我同意在运行时,不会保留类型信息.但请考虑以下类的通用声明:

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

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

那么,为什么我不能用T检查变量的类型,它可以在运行时被Integer替换.而我实际上会做类似“o instanceof Integer”的事情.

在哪些情况下,允许带有类型参数的instanceof会导致故障,从而禁止它?

解决方法

如果在运行时需要T,则需要在运行时提供它.这通常通过传递Class< T>来完成. T必须是.
class SomeClass<T> {
    final T t;

    public SomeClass(Class<T> tClass,T t) {
        if(!tClass.isAssignableFrom(t.getClass()) throw new IllegalArgumentException("Must be a " + tClass);
        this.t = t;
    }

    private SomeClass(T t) {
        this.t = t;
    }

    public static <T> SomeClass<T> of(Class<T> tClass,T t) {
        if(!tClass.isAssignableFrom(t.getClass()) throw new IllegalArgumentException("Must be a " + tClass);
        return new SomeClass(t);
    }
} 

// doesn't compile
SomeClass<Integer> intSomeClass = SomeClass.of(Integer.class,"one");

Class clazz = Integer.class;
// compiles with a warning and throws an IAE at runtime.
SomeClass<Integer> intSomeClass = (SomeClass<Integer>) SomeClass.of(clazz,"one");

// compiles and runs ok.
SomeClass<Integer> intSomeClass = SomeClass.of(Integer.class,1);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读