Private methods and Fields Access with Java Reflection
OK so the first thing first.
What is Java Reflection ?
Java Reflection can be used to dynamically find java classes , locating and execute methods, access fields at run time.
You can find More on : http://docs.oracle.com/javase/tutorial/reflect/index.html
Here is the sample project that I did.
First I create a class called dynamic test and add one private field and four methods including one private methods. Here is the code and its straight forward.
package rd.test;
public class DynamicTest {
private int count;
public void printStar() {
System.out.println("*");
}
public void printStarWithInt(int i) {
System.out.println("* Integer : " + i);
}
public void printStarWithString(String param) {
System.out.println("* String : " + param);
}
public void printStarWithStrings(String param1, String param2) {
System.out.println("* String : " + param1 + " , and " + param2);
}
private void printStarInPrivate() {
System.out.println("* Private : *");
}
}
and here is the class with main method.
package rd;
import rd.test.DynamicTest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException,
InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
Class cls = Class.forName("rd.test.DynamicTest");
Object obj = cls.newInstance();
/**
* calling printstart method without passing any parameters
* */
Method method = cls.getDeclaredMethod("printStar", null);
method.invoke(obj, null);
/**
* calling printStarWithInt method with int parameter
*/
Class[] intParam = new Class[1];
intParam[0] = Integer.TYPE;
method = cls.getDeclaredMethod("printStarWithInt", intParam);
method.invoke(obj, 100);
/**
* calling printStarWithStrings methos with two string parameters
*/
Class[] stringParams = new Class[2];
stringParams[0]=String.class;
stringParams[1]=String.class;
method = cls.getDeclaredMethod("printStarWithStrings", stringParams);
method.invoke(obj, "hi","rajith");
/**
* calling private method in DynamicTest class
*/
method = cls.getDeclaredMethod("printStarInPrivate", null);
method.setAccessible(true);
method.invoke(obj, null);
/**
* setting and getting private fileds
*/
DynamicTest dynamicTest = new DynamicTest();
Field field = cls.getDeclaredField("count");
field.setAccessible(true);
field.setInt(dynamicTest,10);
System.out.println(field.get(dynamicTest));
}
}
No comments:
Post a Comment