1

I would like to do something similar to the following... something like this is kind of easy in dynamic languages, but I'm wondering if it's possible in Java.

public class Person {
    private String name;

    public void setMember(String memberName, String memberValue) {
        // look at memberName, see that it is "name", and then set this.name to whatever memberValue is.
    }
}
3
  • yeah, that would work, but then I have to type that for every member name... I'm trying to avoid having to type similar code over and over again. Commented Sep 28, 2019 at 22:29
  • Possible duplicate of Java: How can I access a class's field by a name stored in a variable? Commented Sep 28, 2019 at 22:33
  • 1
    Are you sure you are not looking for something like a Map<>? Commented Sep 28, 2019 at 22:33

1 Answer 1

2

Maybe misunderstanding, but you could just use

if ("name".equals(memberName)) this.name = memberValue;

But in a more generic sense you can use reflection to set values

Field nameFld = Person.class.getDeclaredField("name");
nameFld.setAccessible(true);
nameFld.set(this, memberValue);
Sign up to request clarification or add additional context in comments.

2 Comments

This sounds about what I'm looking for... reflection, I'll give it a try, thanks.
Cool, please accept it as the answer @BlaineLafreniere

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.