无论如何在给定字段名称的情况下获取对象中某个字段的值?

时间:2011-07-28 06:22:08

标签: java hibernate spring

简而言之, 我想做像

这样的事情
MyObject myObject;

public String getField (String fieldName) {
return myObject.fieldName; // how could I do this since fieldName is a String?
}

背景:

我使用存储过程从数据库中获取数据。

存储过程基本上获取所有列。但我希望用户选择在表格中显示哪一列。

在Hibernate对象中,我拥有与存储过程返回的结果集对应的所有字段。

使用用户想要的字段列表(字符串),有没有办法在给定字段名称的情况下显示Hibernate对象中相应字段的值?

3 个答案:

答案 0 :(得分:4)

您可以使用反射访问它:

public static Object getField(Object target, String fieldName) throws Exception {
    return target.getClass().getDeclaredField(fieldName).get(target);
}

在您的情况下,您只需使用:

myObject.getClass().getDeclaredField(fieldName).get(myObject);

这是对代码的一点测试:

static class A {
    int x = 1;
}

public static void main(String[] args) throws Exception {
    System.out.println(getField(new A(), "x"));
}

输出:

1

答案 1 :(得分:0)

使用reflection

public String getField (String fieldName, Class clazz ,  Object o) {
      Field name = clazz.getField("name");
      name.get(o);
}

答案 2 :(得分:0)

IMO for hibernate最好以accessrog(getter)方法访问值。

我总是使用Apache BeanUtils(http://commons.apache.org/beanutils/v1.8.3/apidocs/index.html

org.apache.commons.beanutils.BeanUtils.getSimpleProperty(yourEntity,fieldName);

或者如果您想使用该字段而不是使用Reflection:

//get the field
java.lang.reflect.Field field = yourEntity.getClass().getField(fieldName);
//set it accessible
boolean oldAccessible = field.isAccessible();
try{
    field.setAccessible(true);
    Object value = field.get(yourEntity);
    return value == null ? "" : value.toString();
}finally{
    field.setAccessible(oldAccessible)
};