I’m currently using reflection to get the declared Fields of a GUI class. However I cannot find a way to be able to typecast the fields into the object that I need.
What I need is to be able to get the actual object of the Field, so if for example the field returned is of type JLabel, I need to be able to typecast the field in JLabel to have access to the object
The following is the code I’m using, however the actual object component is not being retrieved:
for (int i = 0; i< fields.length; i++) {
this.fields.add(fields[i]);
Class<?> fieldType = fields[i].getType();
try {
Component c = (Component) fieldType.newInstance();
System.out.println(c.getX + " " + c.getY());
} catch (InstantiationException ex) {
Logger.getLogger(HeatMap.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(HeatMap.class.getName()).log(Level.SEVERE, null, ex);
}
}
I assume you want to do something like this, don’t you?
I further assume
fieldTypeis a super class ofSomeSubClass, thus you’d get an exception (most probably aClassCastException).Example:
Edit:
To cast the object to something you need use the
instanceofkeyword.Example: