Last active
August 7, 2019 02:39
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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