Tuesday, July 1, 2008

Another victim of The Wall of Erasure

Ahh, Erasure....  Today I was implementing an extension to a class that performs traversing of tree-like object structures (think UI component hierarchies).  The parent class extends another type-parameterized version of an abstract class which provides general tree traversal logic.  The problem is that I wanted to check that the current node is of a type beyond that of the type parameter provided to the parent class.  So to put that into something that might actually be understandable:

public class ParentFinder<T extends Component> extends ComponentVisitor {

private T parent = null;

public ParentFinder() {
// Set up things to travel up the tree...
...
}

public void visit(Component node) {
if(T.class.isAssignableFrom(node.getClass())
parent = (T)node;
}
}

Survey says! *BZZZZ* XXX *BZZZZ* This line is no good thanks to erasure:

  if(T.class.isAssignableFrom(node.getClass())


And, no...you cannot do "instanceof" either. The JVM couldn't tell you if it wanted to. That info is G-O-N-E, gone!

How dare you want to know what you are working with!

No comments: