要查看是否有类具有不依赖于异常的属性,可以使用以下方法:
private Boolean objectHasProperty(Object obj, String propertyName){
List<Field> properties = getAllFields(obj);
for(Field field : properties){
if(field.getName().equalsIgnoreCase(propertyName)){
return true;
}
}
return false;
}
private static List<Field> getAllFields(Object obj){
List<Field> fields = new ArrayList<Field>();
getAllFieldsRecursive(fields, obj.getClass());
return fields;
}
private static List<Field> getAllFieldsRecursive(List<Field> fields, Class<?> type) {
for (Field field: type.getDeclaredFields()) {
fields.add(field);
}
if (type.getSuperclass() != null) {
fields = getAllFieldsRecursive(fields, type.getSuperclass());
}
return fields;
}
而且只需拨打:
objectHasProperty(objInstance, "myPropertyName");
其实没关系的类的实例,看看如果该类财产,但我做了方式,只是要多一点友好。 就得出结论:我做了getAllFields是递归的,让所有的超类方法过于(对我来说这很重要)
之后,如果你想看到什么是财产的价值在所需对象,你可以致电:
PropertyUtils.getProperty(objInstance, "myPropertyName");
记住:如果objInstance
没有该属性,调用上面会抛出NoSuchMethodException
(这就是为什么你需要使用拳头代码,看看如果类的属性)
更多细节真的有助于回答。代码示例也许? – Erwald 2012-04-14 19:26:07