I would like to get the names and values of all attributes of a class instance. That class can be any customized any class, and it can also have object lists, hashmap, tables etc., and can be extented from another class. Actually I mean I would like to get name and value of all attr of a class. so what I need to do should be kind of template. Is it possible? I have written that up to now. any suggestion would be appreciated.
public static void getObjectIntoMap(Object obj) throws IllegalArgumentException, IllegalAccessException {
Field[] field = obj.getClass().getDeclaredFields();
Class<?> c = obj.getClass().getSuperclass();
if(c != Object.class)
getObjectIntoMap(c.getClass());
System.out.println("SSS : "+field.length);
for (Field f : field) {
if(f.getType() == java.util.List.class){
java.util.List<Object> ll = (java.util.List<Object>) f.get(obj);
for (Object o : ll) {
Field[] ff = o.getClass().getDeclaredFields();
for (Field field2 : ff) {
print(field2.getName(), field2.get(o).toString());
}
}
}else if(f.getType() == Hashtable.class){
}
else if(f.getType() == HashMap.class){
}else if(f.getType() == Object[].class){
}
else{
print(f.getName(), f.get(obj).toString());
}
}
}
try http://code.google.com/p/reflections/ ReflectionUtils.getAllFields
returns a Set of all class fields including all super types fields. Now we only need to iterate over them and read instance field values:
Set<Field> fields = ReflectionUtils.getAllFields(X.class, new Predicate() {
public boolean apply(Object input) {
return true;
}});
Map<Field, Object) values = ...
for(Field f : fields) {
f.setAccessible(true);
values.put(f, f.get(obj);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With