Skip to content

Instantly share code, notes, and snippets.

@jdtech3
Last active August 7, 2019 02:39
Show Gist options
  • Save jdtech3/92e1e8ccdf7fa107ba0df532aed5f2c8 to your computer and use it in GitHub Desktop.
Save jdtech3/92e1e8ccdf7fa107ba0df532aed5f2c8 to your computer and use it in GitHub Desktop.
If we have private fields, name 2 different ways we can set the values from outside of the class.
import java.lang.reflect.Field;
class SomeClass {
private int privateValue = 0;
public int getPrivateValue() {
return privateValue;
}
public void setPrivateValue(int privateValue) {
this.privateValue = privateValue;
}
}
public class Test {
public static void main(String args[]) throws NoSuchFieldException, IllegalAccessException {
SomeClass myClass = new SomeClass();
// --- Method 1 ---
// Using setter
System.out.println(myClass.getPrivateValue()); // 0
myClass.setPrivateValue(10);
System.out.println(myClass.getPrivateValue()); // 10
// --- Method 2 ---
// Using java.lang.reflect tools
System.out.println(myClass.getPrivateValue()); // 10
Field privateValue = SomeClass.class.getDeclaredField("privateValue");
privateValue.setAccessible(true);
privateValue.set(myClass, 20);
System.out.println(myClass.getPrivateValue()); // 20
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment