动态代理-编写可生成代理和插入通告的通用方法
package com.itcast.javaenhance.day3;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
public class ProxyTest {
public static void main(String[] args) throws Exception {
Class clazzProxy = Proxy.getProxyClass(
Collection.class.getClassLoader(), Collection.class);
System.out.println(clazzProxy.getName());
System.out.println("--------begin costructors list--------");
Constructor[] constructors = clazzProxy.getConstructors();
for(Constructor constructor: constructors) {
StringBuilder sBuilder = new StringBuilder(constructor.getName());
sBuilder.append('(');
Class[] clazzParams = constructor.getParameterTypes();
for(Class clazzParam: clazzParams) {
sBuilder.append(clazzParam.getName()).append(',');
}
if(clazzParams!=null&&clazzParams.length!=0) {
sBuilder.deleteCharAt(sBuilder.length()-1);
}
sBuilder.append(')');
System.out.println(sBuilder);
}
System.out.println("--------begin methods list--------");
Method[] methods = clazzProxy.getMethods();
for(Method method: methods) {
StringBuilder sBuilder = new StringBuilder(method.getName());
sBuilder.append('(');
Class[] clazzParams = method.getParameterTypes();
for(Class clazzParam: clazzParams) {
sBuilder.append(clazzParam.getName()).append(',');
}
if(clazzParams!=null&&clazzParams.length!=0) {
sBuilder.deleteCharAt(sBuilder.length()-1);
}
sBuilder.append(')');
System.out.println(sBuilder);
}
System.out.println("--------begin create instance object--------");
Constructor constructor2 = clazzProxy.getConstructor(InvocationHandler.class);
class MyInvocationHandler implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return null;
}
}
Collection proxy = (Collection) constructor2.newInstance(new MyInvocationHandler());
System.out.println(proxy);
proxy.clear();
//proxy.size();
Collection proxy2 = (Collection) constructor2.newInstance(new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return null;
}
});
final ArrayList target = new ArrayList();
Collection proxy3 = (Collection) getProxy(target, new MyAdvice());
proxy3.add("lhm");
proxy3.add("zxx");
proxy3.add("flx");
System.out.println(proxy3.size());
System.out.println(proxy3.getClass().getName());
}
private static Object getProxy(final Object target, final Advice advice) {
Object proxy3 = 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 proxy3;
}
}