开发者

Generics runtime check of 'instanceof'

开发者 https://www.devze.com 2023-04-09 16:27 出处:网络
I have an object called Node<Value>. Objects NodeInternal<Value> and NodeLeaf<Value> inherit from Node<Value>.

I have an object called Node<Value>. Objects NodeInternal<Value> and NodeLeaf<Value> inherit from Node<Value>.

I am trying to test what is the type of the object using instanceof as follows:

if (node instanceof NodeInternal). I did not add <Value> because upon runtime, the type is dropped. Without <Value> on NodeInternal however, I get the following warning: NodeInternal is a raw type. References to generic type N开发者_运维问答odeInternal<Value> should be parameterized.

What should I do in this case?


Use an unbounded wildcard:

if (node instanceof NodeInternal<?>) 
  node = ((NodeInternal<Value>) node).SE();


http://www.java2s.com/Code/Java/Language-Basics/Usetheinstanceofoperatorwithagenericclasshierarchy.htm

Use <?>.

You can also play games:

Java: instanceof Generic

0

精彩评论

暂无评论...
验证码 换一张
取 消