Java反射获取全部方法名并调用私有方法

379 阅读1分钟
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Reflection {
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
        Class cat = Cat.class;
        Method[] method = cat.getDeclaredMethods();
        for (Method method2 : method) {
            System.out.println(method2.getName());
        }
        Class[] cArg = new Class[1];
        cArg[0] = String.class;

        System.out.println("获取调用私有方法");
        Cat tr = (Cat) cat.getDeclaredConstructor().newInstance();
        Method method1 = cat.getDeclaredMethod("setInside",cArg);
       
        method1.setAccessible(true); 
        method1.invoke(tr, "参数");
    }
}