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

1
  • 1
    The best way for setting/initializing class variables is using a Constructor. Commented Sep 9, 2016 at 12:29

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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)
Thanks, i updated it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.