javaswingcastingjtreetree-nodes

String variable to a DefaultMutableTreeNode object?


Is it possible to convert a String variable to a DefaultMutableTreeNode object? Please explain. Context:

String s = new String(outputTagName);
Object s2 = (Object) s;
DefaultMutableTreeNode selectedNode2 =(DefaultMutableTreeNode) s2;
DefaultMutableTreeNode parent2 =(DefaultMutableTreeNode) parent;
model.insertNodeInto(selectedNode2, parent2, parent2.getChildCount());

This is the code, I wrote. This is used within an enumeration that traverses the tree in the BreadthFirstSearch fashion. And the 2nf line gives me this error:

java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.tree.DefaultMutableTreeNode at ....

Solution

  • You cannot cast String object to any type other than String or Object, or one of interfaces String implements (Serializable, CharSequence, Comparable). To cast object to some type, the object must be of this type. String object is of type String and not of type DefaultMutableTreeNode. You cannot even make DefaultMutableTreeNode a subclass of String (in which case casting would be possible) as String class is final.