Why “t instanceof T” is not allowed where T is a type parameter and t is a variable?

后端 未结 7 1705
Happy的楠姐
Happy的楠姐 2021-01-05 11:03

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 con

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-05 11:28

    If you need T at runtime, you need to provide it at runtime. This is often done by passing the Class which T has to be.

    class SomeClass {
        final T t;
    
        public SomeClass(Class 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  SomeClass of(Class tClass, T t) {
            if(!tClass.isAssignableFrom(t.getClass()) throw new IllegalArgumentException("Must be a " + tClass);
            return new SomeClass(t);
        }
    } 
    
    // doesn't compile
    SomeClass intSomeClass = SomeClass.of(Integer.class, "one");
    
    Class clazz = Integer.class;
    // compiles with a warning and throws an IAE at runtime.
    SomeClass intSomeClass = (SomeClass) SomeClass.of(clazz, "one");
    
    // compiles and runs ok.
    SomeClass intSomeClass = SomeClass.of(Integer.class, 1);
    

提交回复
热议问题