Java中反射调用私有方法出现NoSuchMethodException

在Java中调用私有方法时除了在调用之前需要设置setAccessible(true)之前,还需要注意getMethod和getDeclaredMethod

调用实例:

package com.jason.test;

//测试类 
class MyTest {
    private void testCall() {
        System.out.println("test");
    }
}

TestReflect.java

package com.jason.test;

import java.lang.reflect.Method;

public class TestReflect {
    public static void main(String[] args) {
        try {
           
            Class classInstance = Class.forName("com.jason.test.MyTest");
//            Method method = classInstance.getMethod("testCall");
            Method method = classInstance.getDeclaredMethod("testCall");
            method.setAccessible(true);
            method.invoke(classInstance.newInstance());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

在调用私有方法时 必须用getDeclaredMethod,getDeclaredMethod和getMethod区别如下:

getMethod:Returns a object that reflects the specified public member method of the class or interface represented by this object.(只能获取public的方法)

getDeclaredMethod:Returns a object that reflects the specified declared method of the class or interface represented by this object. (能获取类中所有方法)

你可能感兴趣的:(Java学习)