给定分层路径,获取字段的值

我有一个包含子属性的对象,它也有子属性等等。

我基本上需要找到检索对象上特定字段值的最佳方法,因为它是一个完整的分层路径作为字符串。

例如,如果对象具有字段company(Object),其字段client(Object)具有字段id(String),则此路径将表示为company.client.id 。 因此,给定一个通向该字段的路径,我试图获取对象的值,我将如何进行此操作?

干杯。

请在下面找到带有getFieldValue方法的Fieldhelper类。 它应该允许您通过拆分字符串然后递归地应用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 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 c = target.getClass(); Field field = getField(c, fieldName); field.setAccessible(true); Object result = field.get(target); return result; } } 

您可以使用Apache Commons BeanUtils PropertyUtilsBean

使用示例:

 PropertyUtilsBean pub = new PropertyUtilsBean(); Object property = pub.getProperty(yourObject, "company.client.id"); 

您需要先拆分字符串以获取单个fieldNames 。 然后,对于每个字段名称,获取所需信息。 您必须遍历您的fieldNames数组。

您可以尝试以下代码。 我没有使用Recursion ,但它会工作: –

 public static void main(String[] args) throws Exception { String str = "company.client.id"; String[] fieldNames = str.split("\\."); Field field; // Demo I have taken as first class that contains `company` Class targetClass = Demo.class; Object obj = new Demo(); for (String fieldName: fieldNames) { field = getFieldByName(targetClass, fieldName); targetClass = field.getType(); obj = getFieldValue(obj, field); System.out.println(field + " : " + obj); } } public static Object getFieldValue(Object obj, Field field) throws Exception { field.setAccessible(true); return field.get(obj); } public static Field getFieldByName(Class targetClass, String fieldName) throws Exception { return targetClass.getDeclaredField(fieldName); }