I\'m playing around with Java\'s reflection API and trying to handle some fields. Now I\'m stuck with identifying the type of my fields. Strings are easy, just do myFi
instanceof works on instances, i.e. on Objects. Sometimes you want to work directly with classes. In this case you can use the asSubClass method of the Class class. Some examples:
1)
Class o=Object.class;
Class c=Class.forName("javax.swing.JFrame").asSubclass(o);
this will go through smoothly because JFrame is subclass of Object. c will contain a Class object representing the JFrame class.
2)
Class o=JButton.class;
Class c=Class.forName("javax.swing.JFrame").asSubclass(o);
this will launch a java.lang.ClassCastException because JFrame is NOT subclass of JButton. c will not be initialized.
3)
Class o=Serializable.class;
Class c=Class.forName("javax.swing.JFrame").asSubclass(o);
this will go through smoothly because JFrame implements the java.io.Serializable interface. c will contain a Class object representing the JFrame class.
Of course the needed imports have to be included.