How to Access Private Methods and Variables of a Java Class in Java

To access Private Fields and Methods of a java class we can use Reflection API.

1.Accessing Private Fields

To access a private field we need to call Class.getDeclaredField(String name) or Class.getDeclaredFields() method,Class.getField(String name) and Class.getFields() methods only return public fields.below is the example code

       // the class whose private variables we want to access
	MyClass myClass=new MyClass();

	//for accessing private variable
	Field f=  MyClass.class.getDeclaredField("myId");
	f.setAccessible(true);
	System.out.println("private variable value is : "+f.get(myClass));

2.Accessing Private Methods

To access a private method we need to call Class.getDeclaredMethod(String name) or Class.getDeclaredMethods() method,Class.getMethod(String name) and Class.getMethods() methods only return public methods.below is the example code


       // the class whose private variables we want to access
	MyClass myClass=new MyClass();

	//for accessing private method
	Method m=MyClass.class.getDeclaredMethod("getData");
	m.setAccessible(true);
	System.out.println("private method value is : "+m.invoke(myClass));

Here is the MyClass Java file.


public class MyClass {
	
	
	private int myId=555;
	private String myName="Vijay";
	
	
	private String getData(){
		
		return  myId+" " +myName;
	}

}
Posted in Java | Leave a comment