Accessing private class members using reflection

We can access private fields and methods outside of class using reflection. Let’s see some example.

In this example, we will try to access the private field defined in the other class.

package reflection1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

class Employee {
	private String name = "Ram";

}

public class Example3 {

	public static void main(String[] args)
			throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException {
		// get Class object
		Class classObj = Class.forName("reflection1.Employee");

		// get all field defined in Example5 class
		System.out.println("-----get filed name defined in Employee class----");
		Field[] fieldArr = classObj.getDeclaredFields();
		for (Field field : fieldArr) {
			String fieldValue = (String) field.get(new Employee());
			System.out.println(fieldValue);
		}

	}
}

Output is –

—–get filed name defined in Employee class—-
Exception in thread “main” java.lang.IllegalAccessException: Class reflection1.Example3 can not access a member of class reflection1.Employee with modifiers “private”
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at reflection1.Example3.main(Example3.java:23)

 

Let’s see how we can access the private field using setAccessible(true).

package reflection1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class Employee {
	private String name = "Ram";

	private void m1() {
		System.out.println(" even i am private method, "
				+ "you can access me outside of class using reflection");
	}
	

}

public class Example3 {

	public static void main(String[] args)
			throws Exception {
		// get Class object
		Class classObj = Class.forName("reflection1.Employee");

		System.out.println("----Access private field using setAccessible(true)------");
		Field[] fieldArr = classObj.getDeclaredFields();
		for (Field field : fieldArr) {
			field.setAccessible(true);
			String fieldValue = (String) field.get(new Employee());
			System.out.println(fieldValue);
		}
		
		System.out.println("-----Access private methods using setAccessible(true)-----");
		Method[] methodArr = classObj.getDeclaredMethods();
		for (Method method : methodArr) {
			method.setAccessible(true);
			method.invoke(new Employee(), null);
		}
		

	}
}

Output is –

—-Access private field using setAccessible(true)——
Ram
—–Access private methods using setAccessible(true)—–
even i am private method, you can access me outside of class using reflection