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

后端 未结 7 1761
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:35

    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 c = new SomeClass();
    SomeClass untyped = (SomeClass)c; // Which type was it?
    SomeClass stringTyped = (SomeClass)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.

提交回复
热议问题