续上篇博客,本文通过demo介绍jdk动态代理
IndexDao.java
package com.jd.project.dao; import com.jd.project.domain.CustWorker; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; public interface IndexDao { public void selectByKey(); }
IndexDaoImpl.java
package com.jd.project.dao; import java.lang.reflect.Proxy; public class IndexDaoImpl implements IndexDao{ @Override public void selectByKey(){ System.out.println("test"); } public static void main(String[] args) { IndexDao indexDao = new IndexDaoImpl(); IndexDao indexDao1 = (IndexDao) new MyInvocationHandler(new IndexDaoImpl()).getProxy(); indexDao1.selectByKey(); } }
MyInvocationHandler.java
package com.jd.project.dao; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class MyInvocationHandler implements InvocationHandler { private Object target; public MyInvocationHandler(Object target) { this.target = target; } public <T> T getProxy(){ return (T)Proxy.newProxyInstance(IndexDaoImpl.class.getClassLoader(),new Class[]{IndexDao.class},this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("proxy start"); return method.invoke(target,args); } }
ProxyClass.java
package com.jd.project.dao; import java.lang.reflect.Proxy; public class ProxyClass{ public void invoke(){ } }