如何获取类的所有属性? [英] how to get all attributes of a class?
问题描述
我想获取类实例的所有属性的名称和值。该类可以是任何定制的任何类,它也可以包含对象列表,散列映射,表格等,并且可以从另一个类中扩展。实际上我的意思是我想得到一个班级的所有attr的名称和价值。所以我需要做的就是模板。可能吗?到目前为止我已经写过了。任何建议将不胜感激。
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());
}
}
}
推荐答案
尝试 http://code.google.com/p/reflections/ ReflectionUtils.getAllFields
返回一组包括所有超类型字段的所有类字段。现在我们只需迭代它们并读取实例字段值:
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);
}
这篇关于如何获取类的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!