How can I set or get a field in a class whose name is dynamic and stored in a string variable?
public class Test {
public String a1;
public String a2;
public Test(String key) {
this.key = 'found'; <--- error
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You have to use reflection:
Class.getField()to get aFieldreference. If it’s not public you’ll need to callClass.getDeclaredField()insteadAccessibleObject.setAccessibleto gain access to the field if it’s not publicField.set()to set the value, or one of the similarly-named methods if it’s a primitiveHere’s an example which deals with the simple case of a public field. A nicer alternative would be to use properties, if possible.