0

All:

I have a data model object in Java like:

class Model {
    String name;
    String email;
}

What I want to do is dynamically determine what attribute I want to set by using a variable like in Javascript object;

String field = "name";

// This is what I try to achieve, not the real code.
New Model().field = "according content";
or 
New Model()[field] = "according content";

Thanks

2
  • you could use reflection Commented Mar 25, 2015 at 0:47
  • @ScaryWombat Thanks for reply. Could you just give out a simple example for my case? Commented Mar 25, 2015 at 0:48

1 Answer 1

1

You could reflection as in this link

In this example they have

   public long chapters = 0;

and can get/set it as

    Field chap = c.getDeclaredField("chapters");
    out.format(fmt, "before", "chapters", book.chapters);
    chap.setLong(book, 12);
    out.format(fmt, "after", "chapters", chap.getLong(book));
Sign up to request clarification or add additional context in comments.

Comments

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.