问题描述:

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);
    }
网友答案:

use #getDeclaredFields() to include private fields, #getFields() is for public.

with private field, due to restrictions refer #setAccessible() method also.

网友答案:

Just a quick addendum:

if(f.getType() == Object[].class

This is probably not what you want (I'm guessing you want to detect all arrays, not just arrays of type Object[]). Instead, you'll want to use something like this:

if(f.getType().getComponentType()!=null)

or, if you want all kinds of object arrays, including e.g. String[], but no primitive arrays, then you could do this:

if(Object[].class.isAssignableFrom(f.getType()))

Apart from that, there are more standardized ways to do what you want to do, which I have shown in previous answers. You can:

  • Use the JavaBeans mechanism to access all bean properties
  • or use Spring's ReflectionUtils to iterate over fields with a callback
相关阅读:
Top