2

I have a model with some properties e.g.

public class Example
{
long id;
String a, b;
int c, d;
boolean e;
}

Now I want to create a method like this

public void update(long id, Map<String, Object> properties)
{
....
}

in this properties map I want to have sth like

properties.put("a","Test"); properties.put("c", 8);

I'm not exactly sure on how to achieve this.

at the end I want to do sth like this:

Example e = new Example(....);
.....
e.update(5L,properties);

can some1 point me to the correct path? I cant figure out a searchterm that doesnt lead me to the Properties or HashMap entries.

thanks in advance

2
  • 1
    You need to look at reflection. Although in many cases that's not actually a good idea... Commented Aug 18, 2014 at 15:18
  • 3
    Why do you have to use fields. Use map as a private field. Commented Aug 18, 2014 at 15:20

1 Answer 1

4

You are searching for the keyword reflection. With reflective access you would write your update method like that:

public void update(long id, Map<String, Object> properties) {
    Object obj = getObjectById(id); // you have to implement that method
    for (String property : properties.keySet()) {
        Field field = obj.getClass().getField(property);
        field.set(obj, properties.get(property));
    }
}

Note, that I did not declare or handle any exceptions that come along with reflection.


A completely other issue: Why do you want to do it this way? Using reflection to update fields of an object smells like a real design issue. You really should consider another model.

Sign up to request clarification or add additional context in comments.

6 Comments

Maybe I am having a design issue. My actual case is that I use Ebean to map a model into a database and populate it via REST. Now I want to enable the update properties method for any object (identified by Id) I get a JSON object with the updated properties and than have to edit it. Would there be a better way to achieve that? Sorry that I didnt state this in the initial question, wanted to keep it simple
Seems like a legal usage of reflection. In fact, many frameworks that map classes to database tables writing objects into them simply use reflection for that.
Thank you, I accepted your answer and will use it (there is already a getObjectById method provided by the Ebean Framwork).
just a note for your solution in line 4 it has to be obj.getClass().getField(..... right? maybe you can fix that so others will see a working solution.
@SebastianD Thanks. I bugfixed it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.