We could use java.lang.reflect to modify a field or call a method which is private of a class
This could be due to no access to source code to change them to public
The following class Person has a private field age and private method growUp:
public class Person { private int age; public Person() { age = 20; } public int getAge() { return age; } private void growUp(int year) { age += year; } }
To call the private growUp, first getting the method object by using getDeclaredMethod:
Method growUp = personA.getClass().getDeclaredMethod("growUp", int.class);
Then setting the accessibility to true:
growUp.setAccessible(true);
Now the method can be invoked:
growUp.invoke(personA, 5); // 5 is the argument of the method
For similar concept, to access the private field, we use getDeclaredField:
Field age = personA.getClass().getDeclaredField("age"); age.setAccessible(true); age.set(personA, 30);
See the main class:
public class MainClass { public static void main(String args[]) throws Exception { Person personA = new Person(); System.out.println("personA's present age: " + personA.getAge()); Method growUp = personA.getClass().getDeclaredMethod("growUp", int.class); growUp.setAccessible(true); growUp.invoke(personA, 5); System.out.println("personA's age after growUp for 5 years: " + personA.getAge()); Field age = personA.getClass().getDeclaredField("age"); age.setAccessible(true); age.set(personA, 30); System.out.println("personA's age after setting to 30 years: " + personA.getAge()); } }
Output:
personA's present age: 20
personA's age after growUp for 5 years: 25
personA's age after setting to 30 years: 30