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;
	}

}
Advertisements
This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s