jdk代理

来源:互联网 发布:java调用groovy脚本 编辑:程序博客网 时间:2024/06/05 16:03

面向接口的动态代理实现方式:

先写一个接口:

package com.muou.tinterface;public interface StuInterface {public String goSchool();}

实现这个接口:

package com.muou.impl;import com.muou.tinterface.StuInterface;public class StuInterfaceImpl implements StuInterface{public String goSchool() {System.out.println("上学");return "学分10分";}}

编写代理类:

package com.muou.proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class JDKProxy implements InvocationHandler{//定义一个对象,接受要代理的对象private Object targat;public JDKProxy(Object targat){this.targat = targat;}//增强要代理 对象的功能,增加前置和后置处理public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {System.out.println("上学之前吃饭");//被代理对象方法真正执行的地方Object result = method.invoke(targat, args);System.out.println("放学之后写作业");return result;}public Object getProxy(){//获取代理对象return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), targat.getClass().getInterfaces(), this);}}


编写测试方法:

@Testpublic void testJDKProx() {StuInterfaceImpl interface1 = new StuInterfaceImpl();StuInterface proxy = (StuInterface)new JDKProxy(interface1).getProxy();String result = proxy.goSchool();System.out.println(result);}


执行结果:

上学之前吃饭上学放学之后写作业学分10分


当做笔记记录