Accessing Private Methods
Call Class.getDeclaredMethod(String name, Class[] paramTypes) or Class.getDeclaredMethods() method to obtain the private/public methods.
The methods Class.getMethod(String name, Class[] parameterTypes) and Class.getMethods() methods only return public methods.
package reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class PrivateObject {
private String string;
publicPrivateObject (String string) {
this.string= string;
}
private String getPrivateMethod() {
return string;
}
}
public class TestReflectionMethod {
public static voidmain(String[] args) {
PrivateObject pvtObj = newPrivateObject("Private method");
try {
Method privateMethod =
PrivateObject.class.getDeclaredMethod
("getPrivateMethod",null);
PrivateObject.class.getDeclaredMethod
("getPrivateMethod",null);
/** SecurityException -if the request is denied. */
privateMethod.setAccessible(true);
String returnValue =
(String) privateMethod.invoke(pvtObj, null);
System.out.println("using reflection="+returnValue+" accessed!!");
} catch(IllegalAccessException e) {
} catch(InvocationTargetException e) {
} catch(NoSuchMethodException e) {
}
}
}
Output: using reflection = Private method accessed!!
No comments:
Post a Comment