JDK代理

来源:互联网 发布:python中time.sleep 编辑:程序博客网 时间:2024/06/01 10:44
package net.itdos.junit;import net.itdos.aop.JDKProxy;import net.itdos.service.PersonService;import net.itdos.service.impl.PersonServiceBean;import org.junit.BeforeClass;import org.junit.Test;public class AOPJunit {@BeforeClasspublic static void setUpBeforeClass() throws Exception {}@Testpublic void AOP(){JDKProxy factory = new JDKProxy();PersonService personService = (PersonService)factory.CreateProxyIntance(new PersonServiceBean("fff"));personService.save();}}



package net.itdos.service.impl;import net.itdos.service.PersonService;public class PersonServiceBean implements PersonService {public PersonServiceBean() {super();}public PersonServiceBean(String name) {super();this.name = name;}private String name;public String getName() {return name;}public void save(){System.out.println("这是个save方法");}public void update(){System.out.println("这是个update方法");}}

package net.itdos.aop;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import net.itdos.service.impl.PersonServiceBean;public class JDKProxy implements InvocationHandler {public Object targetObject;public Object CreateProxyIntance(Object targetObject){this.targetObject = targetObject;return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(), this.targetObject.getClass().getInterfaces(), this);}@Overridepublic Object invoke(Object object, Method method, Object[] args)throws Throwable {Object  result = null;PersonServiceBean personServiceBean = (PersonServiceBean)this.targetObject;if(personServiceBean.getName() != null){result = method.invoke(targetObject, args);}return result;}}


原创粉丝点击