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.
-
1The best way for setting/initializing class variables is using a Constructor. – Ezio Sep 09 '16 at 12:29
2 Answers
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)

- 183
- 7

- 11,357
- 8
- 43
- 88
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.

- 322
- 1
- 3
- 16
-
I think that this not true for all, you can do it in other scopes too, but it depends where are you setting the value (in class method or others) – Mikel Sep 09 '16 at 12:28
-