如何通过反射调用(黑进)私有方法

私有方法的api不一定就是完全安全的, 单例模式的私有构造器也不一定能保证自己一定是单例

在产品平台上做开发, 有时候你总会需要jad, 继承, cglib 或者 反射

package name.lizhe;

public class Employee {
    
    private void setSalary(int i){
        System.out.println("changed salary to:"+i);
    }
    
}
package name.lizhe;

import java.lang.reflect.InvocationTargetException;

public class Executor {

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {

        Employee emp = new Employee();

        Class[] cArg = new Class[1];
        cArg[0] = int.class;

        java.lang.reflect.Method m = Employee.class.getDeclaredMethod("setSalary", cArg);
        m.setAccessible(true);
        m.invoke(emp, 10000);
    }

}
 

如果是私有构造方法的话略微 有些不同

package name.lizhe;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Executor {

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException, InstantiationException {

        Employee emp = Employee.getInstance();

        Class[] cArg = new Class[1];
        cArg[0] = int.class;

        Constructor<Employee> m = Employee.class.getDeclaredConstructor();
        m.setAccessible(true);
        Employee emp2 = (Employee) m.newInstance(null);
        
        System.out.println(emp==emp2);
    }

}