Java Reflection for setting attributes

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;
  //etc. etc.  Many String attributes

  // … constructor and other stuff are omitted

  // here is my method for "dynamically" setting each attribute
  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");
// etc.

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... , - .

!

+3
3

, (.. )

. . , , . ; / ( ). , ++, Java Python.

, , ... well

  • , . ( ?)
  • . ( - ?)

"final", (-) .

+1

setter - , , , , .

IDE (, Eclipse NetBeans) getter setter .

0
  • , fld.setAccessible(true);
  • Yes, why don't you just set the fields directly and avoid reflection? It does not look like you are doing something dynamic. It's just that they are private - why? Perhaps you want to expose getters / setters and make private fields? If so, you should just call public developers.
0
source

Source: https://habr.com/ru/post/1769663/


All Articles