I'm trying to access a private method, but it doesn't let me to, and throws the exception. How can I avoid the exception? I've tried a lot of other questions, but they all just point to using setAccessible(true), which I'm already using right now.
import java.lang.reflect.*;
class Reflection {
public static void main (String[] args) {
try {
//Get class instance
ReflectionExamples re = new ReflectionExamples();
Class<?> c = re.getClass();
System.out.println("Class name is " + c.getName());
//Get constructor of class
Constructor<?> cons = c.getConstructor();
System.out.println("Constructor name is " + cons.getName());
System.out.println("List of methods are:");
//Iterate all methods
Method[] methods = c.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
//Desired method to call
Method call = c.getDeclaredMethod("e");
//Unlock the private Method
call.setAccessible(true);
//Invoke the Method
call.invoke(re);
//Desired method to call
Method call2 = c.getDeclaredMethod("a");
//Invoke the method
call2.invoke(c);
} catch(Throwable e) {
System.err.println(e);
}
}
}
class ReflectionExamples {
private String string = "String222222";
public int i = 0;
public ReflectionExamples() {
string = "String";
}
private void e() {
System.out.println("Char entered is not valid.");
}
public void f(char a) {
System.out.println("awojiewfihuerhkuah");
}
public void a() {
System.out.println(string);
}
}
And I get:
java.security.AccessControlException: access denied ("java.lang.reflect.ReflectPermission" "suppressAccessChecks")
Aucun commentaire:
Enregistrer un commentaire