java 动态代理的案例使用与解析
解析在代码注释中,不多做解释
import java.lang.reflect.Method;
//简单的方法拦截接口
public interface Advice {
void beforeMethod(Method method);
void afterMethod(Method method);
}
import java.lang.reflect.Method;
//简单的接口实现
public class MyAdvice implements Advice {
long beginTime = 0;
public void afterMethod(Method method) {
// TODO Auto-generated method stub
System.out.println("after method:" + method.getName());
long endTime = System.currentTimeMillis();
System.out.println(method.getName() + " running time of " + (endTime - beginTime));
}
public void beforeMethod(Method method) {
// TODO Auto-generated method stub
System.out.println("before method:" + method.getName());
beginTime = System.currentTimeMillis();
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//获取java 代理对象的工具类
public class ProxyUtil {
public static Object getProxy(final Object target,final Advice advice) {
// System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");//生成的代理class对象在工程目录下的com\sun\proxy
Object proxy;
proxy= Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforeMethod(method);
Object retVal = method.invoke(target, args);
advice.afterMethod(method);
return retVal;
}
}
);
return proxy;
}
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
//使用Jdk 动态代理类必须实现接口,代理的方法包括接口中方法和Object的基础方法,验证想要被代理的方法必须代理
//类实现接口中定义的方法
public class ProxyEg1 {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ProxyEg1 eg1 = new ProxyEg1();
// ArrayList<Integer> eg1 = new ArrayList<>();
Object proxy = ProxyUtil.getProxy(eg1, new MyAdvice());
Method method = ProxyEg1.class.getMethod("method");
System.out.println(method);
System.out.println(proxy);
// method.invoke(proxy);//报错 object is not an instance of declaring class,表明proxy和ProxyEg1 没有继承关系
System.out.println("eg1 end-------");
Method[] methods = proxy.getClass().getMethods();//打印代理类的所有方法
for (Method m : methods) {
System.out.println(m.getName());//发现并没有method方法
}
System.out.println("eg2 end-------");
ArrayList<Integer> eg2 = new ArrayList<>();
Collection p1 =(Collection) ProxyUtil.getProxy(eg2, new MyAdvice());
System.out.println(p1.getClass());
System.out.println(p1);
p1.add(1);
//实现代理的案例
final ArrayList target = new ArrayList();
Collection proxy3 = (Collection)ProxyUtil.getProxy(target,new MyAdvice());
proxy3.add("zxx");
proxy3.add("lhm");
proxy3.add("bxd");
System.out.println(proxy3.size());
System.out.println(proxy3.getClass().getName());
}
public void method(){
System.out.println("method run");
}
}