Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get all attributes of a class?

Tags:

java

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());
        }
    }
}
like image 758
Emilla Avatar asked Feb 14 '23 05:02

Emilla


1 Answers

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);
    }
like image 134
Evgeniy Dorofeev Avatar answered Feb 16 '23 18:02

Evgeniy Dorofeev