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

后端 未结 7 1755
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:27

    Because of type erasure, this never works. At runtime, you only know that your class has a type parameter T, but not which type it is for a given instance. So you can't determine whether an object is of type T to begin with, because you don't know what T is, not because it would cause some sort of trouble.

    If you need to do this sort of runtime check, pass a type token to your object explicitly:

    SomeClass(Object o, Class type) {
        System.out.println(type.isInstance(o));
    }
    

提交回复
热议问题