Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value for object field by reflection in java

First, I have an object like that:

public class Entity {
    public int data1;
    public String data2;
    public float data3;
    public SubEntity data4;
}

public class SubEntity{
    public int id;
    public SubEntity(int id){
      tis.id = id;
    }
}

And a HashMap:

  HashMap<String, Object> map = new HashMap<String, Object>();
  map.put("data1", 1);
  map.put("data2", "name");
  map.put("data3", 1.7);
  map.put("data4", new SubEntity(11));

I need the right way to set value for all field of entity dynamic by use reflect from hashmap. Something like this:

    for (Field f : entity.getClass().getDeclaredFields()) {
       String name = f.getName();
       Object obj = map.get("name");
       // Need set value field base on its name and type. 

} 

How can I achieve that? Assume I have many sub classes in entity.

like image 511
ductran Avatar asked Oct 12 '12 10:10

ductran


People also ask

How do you assign a value to a field in Java?

type variableName = value; Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

How do you change the value of the private variable in Java using reflection?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

How do you set a field value?

SetFieldValue(value = 10000.0); The FieldByName method returns the field object that represents the given field (salary_fld, in this example), and the SetFieldValue methods uses that field object to set the value of the field. If this method is successful, it returns ER_OK.


1 Answers

If you want to go the reflection route, then why not use Field.set(Object, Object) and its more type-safe siblings (see doc)

f.set(myEntity, obj);

Note. You may need to make the field accessible first if it's private/protected.

However if you can I would perhaps delegate to the object and it could populate itself via the map e.g.

myEntity.populateFromMap(myMap);

and do the hard(ish) work within your class.

like image 61
Brian Agnew Avatar answered Oct 19 '22 18:10

Brian Agnew