-1

I have a list variable in a class which does not have a setter method. Is there any way that I can set value for the list object.

user1019072
  • 299
  • 1
  • 7
  • 17

2 Answers2

3

If you are in the class itself, as in, inside a method, and the variable is marked private, public, or protected, then use this:

m_name = value;

If the field is public, and you need access outside the class, then do:

classinstance.m_name = value;

Of course if you need the variable to be constructed in the instantiation of the class, then you need to put the instantiation code for the list in the constructor. Then again, you could use reflection like this:

import java.lang.reflect.Field;
ClassName classInstance = new ClassName();
Field member_name = classInstance.getClass().getDeclaredField("private_var_name");

// this is for private scope
member_name.setAccessible(true);

member_name.set(classInstance, /*value*/);

Of course, I don't recommend doing the above, since it definitely breaks encapsulation, and it looks more like a hack than clean code:

(Source)

Gon
  • 183
  • 7
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
0

When the attribute is public you can access it like this. When your the attribute is protected, the class has to be in the same package as your class.

obj.value = newValue;

When it is private you can do it by refelction.

Huntro
  • 322
  • 1
  • 3
  • 16