首页 > 解决方案 > 为什么我不能使用 Java 反射 API 访问私有方法?

问题描述

我正在尝试访问一个私有方法,但它不允许我访问,并引发异常。我怎样才能避免异常?我已经尝试了很多其他问题,但它们都只是指向使用我现在已经在使用的 setAccessible(true)。

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

我得到:

java.security.AccessControlException: access denied ("java.lang.reflect.ReflectPermission" "suppressAccessChecks")

标签: javareflection

解决方案


推荐阅读