反射调用私有方法

package mianshi;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectTest {

    public static void  main(String[] args) throws NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        
        
        A a = new A();
//      a.method2();
        
        Method method1 = Class.forName("mianshi.A").getDeclaredMethod("method1");
        method1.setAccessible(true);
        method1.invoke(a);
    
    }
    
}


class A{
    private void method1(){
        System.out.println("私有方法");
    }
    
    public void method2(){
        System.out.println("公有方法");
    }
}

你可能感兴趣的:(反射调用私有方法)