我有一个包含子属性的对象,它也有子属性等等.
我基本上需要找到检索对象上特定字段值的最佳方法,因为它是一个完整的分层路径作为字符串.
例如,如果对象具有字段company(Object),其字段client(Object)具有字段id(String),则此路径将表示为company.client.id.因此,给定一个通向该字段的路径,我试图获取对象的值,我将如何进行此操作?
干杯.
Rad*_*FID 14
您可以使用Apache Commons BeanUtils PropertyUtilsBean.
使用示例:
PropertyUtilsBean pub = new PropertyUtilsBean();
Object property = pub.getProperty(yourObject, "company.client.id");
Run Code Online (Sandbox Code Playgroud)
请找到下面的Fieldhelper类及其getFieldValue方法。它应该允许您通过分割字符串然后递归应用getFieldValue,将结果对象作为下一步的输入来快速解决问题。
package com.bitplan.resthelper;
import java.lang.reflect.Field;
/**
* Reflection help
* @author wf
*
*/
public class FieldHelper {
/**
* get a Field including superclasses
*
* @param c
* @param fieldName
* @return
*/
public Field getField(Class<?> c, String fieldName) {
Field result = null;
try {
result = c.getDeclaredField(fieldName);
} catch (NoSuchFieldException nsfe) {
Class<?> sc = c.getSuperclass();
result = getField(sc, fieldName);
}
return result;
}
/**
* set a field Value by name
*
* @param fieldName
* @param Value
* @throws Exception
*/
public void setFieldValue(Object target,String fieldName, Object value) throws Exception {
Class<? extends Object> c = target.getClass();
Field field = getField(c, fieldName);
field.setAccessible(true);
// beware of ...
// http://docs.oracle.com/javase/tutorial/reflect/member/fieldTrouble.html
field.set(this, value);
}
/**
* get a field Value by name
*
* @param fieldName
* @return
* @throws Exception
*/
public Object getFieldValue(Object target,String fieldName) throws Exception {
Class<? extends Object> c = target.getClass();
Field field = getField(c, fieldName);
field.setAccessible(true);
Object result = field.get(target);
return result;
}
}
Run Code Online (Sandbox Code Playgroud)