JDK动态代理

来源:互联网 发布:淘宝怎么搜不到东西了 编辑:程序博客网 时间:2024/06/06 17:24

步骤:

1.定义拦截器

2.用代理类生成代理对象(要将被代理的对象手动传入)


注意:使用JDK动态代理的时候,目标类必须要实现接口,否则在使用Proxy.newProxyInstance方法的时候是无法强转为目标类的(必须强转为目标类的接口类型,所以无接口就不能强转了)。


定义一个接口:

public interface Person {public void study();public void work();}

定义一个实现类:

public class Student implements Person {public void study() {System.out.println("学生学习");}public void work() {System.out.println("学生工作");}}

定义一个拦截器(实现InvocationHandler,如果用的是匿名内部类,就可省略此步骤):

/** * 实现InvocationHandler */public class MyInterceptor implements InvocationHandler{    //传入一个需要被代理的对象    private Object target;    public MyInterceptor(Object target){        this.target = target;    }        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//invoke是在目标方法调用的时候运行的        //第一个参数代理实例,method,第二个参数为目标类方法生成的method实例,第三个参数是方法的参数        //这里如果使用method.invoke(proxy, args);就会进入死循环,所以要从外部传入一个需要被代理的对象        /**         * 这里还可以对指定的方法进行指定的处理,例如         * if("add".equals(method.getName())){}         */        return method.invoke(target, args);    }}

测试类:

public class TestProxy {public static void main(String[] args) {final Person  p = new Student();//方法一:匿名内部类/*Person stu = (Person)Proxy.newProxyInstance(Person.class.getClassLoader(),p.getClass().getInterfaces(), new InvocationHandler() {public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//System.out.println("调用动态代理invoke");//每调用一个方法,都会在这里执行一次,调用代理类的方法return method.invoke(p, args);}});*///方法二:新建一个类实现InvocationHandler     Proxy.newProxyInstance是新建一个代理类(类加载器,被代理类实现的接口数组,拦截器)//由于用Person对象能够接收代理类返回的代理对象,由此可以推断出,代理类是实现了Person接口的Person stu = (Person)Proxy.newProxyInstance(Person.class.getClassLoader(),p.getClass().getInterfaces(), new MyInterceptor(p));stu.study();stu.work();}}



原创粉丝点击