Ensuring type safety, honoring supertype contract
If I can't do instanceof T in Java (due to type erasure), then how do I write a generic tree node? setUserObject() accepts Object, not T. Do I have no better choice than making clients pass Class literals? public class ItemTreeNode extends DefaultMutableTreeNode { public ItemTreeNode(T userObject) { super(userObject); } @Override @SuppressWarnings("unchecked") public void setUserObject(Object userObject) { super.setUserObject((T) userObject); // would throw ClassCastException if it's not T } @Override @SuppressWarnings("unchecked") public T getUserObject() { return (T) super.getUserObject(); } }

If I can't do instanceof T
in Java (due to type erasure), then how do I write a generic tree node? setUserObject()
accepts Object
, not T
. Do I have no better choice than making clients pass Class
literals?
public class ItemTreeNode extends DefaultMutableTreeNode {
public ItemTreeNode(T userObject) {
super(userObject);
}
@Override
@SuppressWarnings("unchecked")
public void setUserObject(Object userObject) {
super.setUserObject((T) userObject); // would throw ClassCastException if it's not T
}
@Override
@SuppressWarnings("unchecked")
public T getUserObject() {
return (T) super.getUserObject();
}
}