JDK动态代理实现
程序员文章站
2022-07-15 10:27:09
...
JDKProxy.java
package com.company;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class JDKProxy {
public static void main(String[] args){
UserDaoImpl userDao = new UserDaoImpl();
Class[] interfaces={UserDao.class};
UserDao dao=(UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(),interfaces,new UserDaoProxy(userDao));
int result=dao.add(1,2);
System.out.println(result);
}
}
class UserDaoProxy implements InvocationHandler{
private Object obj;
public UserDaoProxy(Object obj){
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//方法之前
System.out.println("方法之前执行..."+method.getName()+" :传递的参数..."+ Arrays.toString(args));
//被增强的方法执行
Object res = method.invoke(obj,args);
//方法之后
System.out.println("方法之后执行..."+obj);
return res;
}
}
UserDao.java
package com.company; public interface UserDao { public int add(int a,int b); //public String update(String id); }
UserDaoImpl.java package com.company; public class UserDaoImpl implements UserDao{ @Override public int add(int a, int b) { System.out.println("add方法执行了"); return a+b; } /*@Override public String update(String id) { System.out.println("update方法执行了"); return id; }*/ }