4

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 NodeInternal<Value> should be parameterized.

What should I do in this case?

darksky
  • 20,411
  • 61
  • 165
  • 254

2 Answers2

1

Use an unbounded wildcard:

if (node instanceof NodeInternal<?>) 
  node = ((NodeInternal<Value>) node).SE();
erickson
  • 265,237
  • 58
  • 395
  • 493
  • That means it can take any object. Is that good implementation? – darksky Oct 01 '11 at 20:35
  • 1
    @Nayefc If worried about that then add a method on node that you can override in its subclasses and then call that instead of instanceOf – mmmmmm Oct 01 '11 at 20:38
  • 1
    @Nayefc As you note, because of generic type erasure, that's all the type information you have. The `node` variable will have a generic type parameter; make sure that your code compiles without type-safety warnings. – erickson Oct 01 '11 at 20:42
  • Sounds good. Well regarding that, my `NodeInternal` has a method called `SE()`. So in `if (node instanceof NodeInternal>)`, I have `node = ((NodeInternal>) node).SE();`. I get the following error however, `Type mismatch: cannot convert from Node to Node`. It asks me to change the Node argument that gets passed in from the function from `insert(Node)` to `insert(Node>)` which is a wrong suggestion (breaks the code). How would I invoke a method on node only if its available in NodeInternal when IT IS NodeInternal? C++ is a lot easier when doing that. – darksky Oct 01 '11 at 21:05
  • @Nayefc - Please see my edit; you should cast the `node` to `NodeInternal` instead of `NodeInternal>` – erickson Oct 01 '11 at 23:29
0

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

Use <?>.

You can also play games:

Java: instanceof Generic

Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302