I have a class that has a lot of custom / retrievable attributes. I would like to use reflection to set these attributes, but I have 2 questions about my implementation
Here is some cleaned code from my class
class Q {
public String question_1;
public String question_2;
public String question_3;
public String answer_1;
public String answer_2;
public String answer_3;
public void set_attribute(String a_raw_string, String my_field) {
try {
Class cls = Class.forName("com.xyz.models.Q");
Field fld = cls.getField(my_field);
fld.set(this, a_raw_string);
}
catch (Throwable e) {
System.err.println(e);
}
}
Then I set the various fields as follows:
Q q = new Q();
q.set_attribute("abcde", "question_1");
q.set_attribute("defgh", "question_2");
This works (i.e., instance variables are set when calling set_attribute.
However, they only work when instance variables are declared public. When they are declared private, I get a NoSuchFieldException
1:. , ? , set_attribute , .
2: , (.. ). ?
, , , , setter... , - .
!