给定分层路径,获取字段的值 [英] Get the value of a field, given the hierarchical path
问题描述
我有一个包含子属性的对象,它也有子属性等等。
I have an object that contains sub properties, which also have sub properties and so on.
我基本上需要找到检索对象上特定字段值的最佳方法,因为它的完整层次路径为字符串。
I basically need to find the best way to retrieve the value of a particular field on the object, given it's full hierarchical path as a string.
例如,如果对象具有字段company(Object),其字段client(Object)具有字段id(String),则此路径将表示为 company.client.id
。因此,给定一个通往该领域的路径,我试图获得一个物体的价值,我该怎么做?
For example, if the object has the field company (Object) which has the field client (Object) which has the field id (String), this path will be represented as company.client.id
. Therefore, given a path to the field i'm trying to get the value of on an object, how would I go about doing this?
干杯。
推荐答案
请在下面找到 Fieldhelper
类 getFieldValue
方法。
它应该允许你通过
分割你的字符串然后以递归方式应用 getFieldValue
来快速解决你的问题,将结果对象作为输入下一步。
Please find below Fieldhelper
class with getFieldValue
method.
It should allow you to solve your problem pretty quickly by
splitting your string and then applying the the getFieldValue
recursively, taking the result object as input for the next step.
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;
}
}
这篇关于给定分层路径,获取字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!