利用反射机制调用对象的私有方法和属性
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestPrivate {
    public static void main(String[] args) throws Exception{
        //使用反射机制调用对象的私有方法
        Private p = new Private();
        Class<?> classType = p.getClass();
        Method method = classType.getDeclaredMethod("sayHello", new Class[]{String.class});
        method.setAccessible(true); //压制java的访问控制检查
        String str = (String)method.invoke(p, new Object[]{"tom"});
        System.out.println(str);
         
        //使用反射机制调用对象的私有属性
        Field field = classType.getDeclaredField("name");
        field.setAccessible(true);
        field.set(p, "lisi");
        String name = (String)field.get(p);
        System.out.println(name);
    }
}
class Private{
    private String name = "zhangsan";
     
    private String sayHello(String name){
        return "hello "+name;
    }
}