import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import javax.swing.JComponent;
import javax.swing.JLabel;
public class Test
{
JComponent component;
final HashMap<String,Object> props = new HashMap<String,Object>();
public Test(JComponent component)
throws Exception
{
if (component == null) throw new IllegalArgumentException("The Component mustn't be null!!");
this.component = component;
iterateProperties( props, component);
}
public HashMap<String,Object> getProperties() {
return props;
}
private static void iterateProperties( final HashMap<String,Object> props, final Object instance) {
iterateFields( props, instance.getClass(), instance);
iterateMethods( props, instance.getClass(), instance);
}
private static void iterateFields( final HashMap<String,Object> props, final Class cls, final Object instance) {
if ( cls == null) return;
Field[] flds = cls.getDeclaredFields();
for (Field f: flds) {
if ( Modifier.isStatic(f.getModifiers())) continue;
try {
f.setAccessible( true);
props.put( f.getName(), f.get( instance));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
iterateFields( props, cls.getSuperclass(), instance);
}
private static void iterateMethods( final HashMap<String,Object> props, final Class cls, final Object instance) {
if ( cls == null) return;
Method[] mthds = cls.getDeclaredMethods();
for (Method m : mthds) {
if ( Modifier.isStatic(m.getModifiers())) continue;
if ( m.getReturnType() == null) continue; //--- skip void methods
if ( m.getParameterTypes().length > 0) continue; //--- skip methods that required parameters
String mn = m.getName();
if ( mn.startsWith( "get") || (mn.startsWith( "has"))) {
mn = mn.substring( 3);
} else if ( mn.startsWith( "is")) {
mn = mn.substring( 2);
} else {
continue;
}
if ( mn.length() == 0) continue;
if ( !Character.isUpperCase( mn.charAt(0))) continue;
if ( props.containsKey( mn)) continue; //--- skip getter if a field with the same name already exists
try {
m.setAccessible( true);
props.put( mn, m.invoke( instance, new Object[0]));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
iterateMethods( props, cls.getSuperclass(), instance);
}
public static void main(String[] args) throws Exception {
JLabel l = new JLabel("Moep");
l.setLocation(3, 5);
HashMap<String,Object> props = new Test(l).getProperties();
for ( String key : props.keySet()) {
System.out.println( key + " : " + props.get( key));
}
}
}