Reputation: 59
In the below code snippet how can I set the value of a and b without using the setter method? Is it possible? Can I call the private constructor in the public constructor?
public class ABC {
private int a;
private int b;
public ABC() {
}
private ABC(int a, int b) {
this.a = a;
this.b = b;
}
}
ABC abc = new ABC();
Upvotes: 1
Views: 6904
Reputation: 26340
If I understand you correctly, your actual question is
Can I call the private constructor in the public constructor?
and nothing really related to setters.
Yes, you can call one constructor from another. In your example code this would look like this:
public ABC() {
this(0, 0); // initialze a and b via the private constructor
}
Upvotes: 0
Reputation: 161
You can use Java reflection, but this is considered to be bad practice and should be avoided. However, if you really need to:
ABC abc = new ABC();
Field abc_a = abc.getClass().getDeclaredField("a");
abc_a.setAccessible(true);
abc_a.set(abc, 20);
Explanation
Field abc_a = abc.getClass().getDeclaredField("a");
In java, there is a set of tools called Reflection, whose intended use is to allow for fields in classes to be dynamically set. A practical use of this is the GSON library, which reads JSON and automatically fills in the corresponding values in a class.
Every class has a Class
object to assist with reflection, and every instance of an object has a method called getClass()
. Calling this method will give you the Class
object representing that class and using that, you can then invoke the getDeclaredField(fieldName)
method which will return a Field
object that allows you to do a variety of things to that field, one of which is setting the value.
abc_a.setAccessible(true);
Because the field being referenced to is private, this must be invoked to allow it to be accessed. If it was public, this step could be omitted.
abc_a.set(abc, 20);
This finally changes the value of the field a
in the ABC
class. The first parameter is the object you wish to change the value of, and the second parameter is the new value. Note that Field objects don't store class information, so if you wished to change the value of a different instance of ABC
, you could use the same Field object and just change the first parameter.
Upvotes: 9