复制代码
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Test {
    public static void main(String[] args) {
        Student stu = new Student();
        stu.eat("蛋糕");
        stu.study();

        //如何在不改变Student类中任何代码的前提下,通过study()方法输出一句话:我在认真的学习中。。。
        //实现方式:使用动态代理
        /*
        动态代理:
        参数详解:ClassLoader loader  :类加载器,和被代理对象使用相同的加载器(被代理对象的类加载器)
                Class<?>[] interfaces  : 接口类型的class数组,和被代理对象使用相同的接口(被代理对象实现的接口)
                InvocationHandler : 代理规则,完成代理增强的功能
         */
        //代理对象StudentIntafce  被代理对象:Student
        StudentIntafce stuIntafce = (StudentIntafce) Proxy.newProxyInstance(stu.getClass().getClassLoader(), new Class[]{StudentIntafce.class}, new InvocationHandler() {
            //执行Student类中方法都会经过invoke方法
            //对method进行判断,如果是study,就进行增强,如果是其他方法,调用stu对象原有的功能即可
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if ("study".equals(method.getName())) {
                    System.out.println("我在认真的学习中。。。");
                    return null;
                } else {
                    return method.invoke(stu, args);
                }
            }
        });

        stuIntafce.eat("烧烤");
        stuIntafce.study();
    }
}
复制代码
复制代码
public class Student implements StudentIntafce{

    public void eat(String food) {
        System.out.println("吃" + food);
    }

    public void study(){
        System.out.println("在学习中。。。");
    }
}
复制代码
public interface StudentIntafce {

    void eat(String food);

    void study();
}