简体   繁体   中英

Is there anyway to get the value of a certain field in an object given the field name?

In short, I want to do something like

MyObject myObject;

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

Background:

I am getting data from the database using a stored procedure.

The stored procedure basically gets all the columns. But I want the user to choose which column to display in the table.

In the Hibernate object, I have all the fields corresponding to the resultset returned by the stored procedure.

With the list of fields (Strings) that the user wants, is there a way to display the value of the corresponding field in the Hibernate object given the field name?

You can access it using reflection:

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

In your case, you'd just use:

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

Here's a little test of the code:

static class A {
    int x = 1;
}

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

Output:

1

Use reflection

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

IMO for hibernate it is better to access the value throgh the accesser (getter) methods.

I always use Apache BeanUtils for that( http://commons.apache.org/beanutils/v1.8.3/apidocs/index.html )

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

Or if you want to use the field than use 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)
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM