目录
JDK动态代理
第一种写法:
public interface HelloInterface {
void sayHello();
}
public class HelloImpl implements HelloInterface {
@Override
public void sayHello() {
System.out.println("你好!");
}
}
public class HelloProxy implements InvocationHandler {
private Object obj;
public Object getProxy(Object obj) {
this.obj = obj;
Class<?> clazz = obj.getClass();
return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnObj = null;
String name = method.getName();
System.out.println("执行方法 " + name + "前...");
returnObj = method.invoke(obj, args);
System.out.println("执行方法 " + name + "后...");
return returnObj;
}
}
public static void main(String[] args) throws Exception {
HelloProxy hp = new HelloProxy();
HelloInterface hi = (HelloInterface) hp.getProxy(new HelloImpl());
hi.sayHello();
}
第二种写法(以HashSet集合为例):
public static <T> Set<T> getSetProxy(Class<T> t) {
final Set<T> set = new HashSet<T>();
Class<?> clazz = set.getClass();
return (Set<T>) Proxy.newProxyInstance(clazz.getClassLoader(),
clazz.getInterfaces(), new InvocationHandler() {//匿名内部类
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
String methodName = method.getName();
//为add方法增添新功能:
if("add".equals(methodName)) {
result = set.add((T) args[0]);
if(!(boolean) result) {
System.err.println(args[0] + "元素重复,无法添加!");
}
}else {
result = method.invoke(set, args);
}
return result ;
}
});
}
Cglib代理(代理未实现接口的类)
也叫子类代理,构建一个子类从而实现对目标对象功能的扩展。
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
public class ProxyFactory implements MethodInterceptor {
private Object target;
public ProxyFactory(Object target) {
this.target = target;
}
public Object getProxyInstance() {
Enhancer e = new Enhancer();
e.setSuperclass(target.getClass());//设置父类
e.setCallback(this);//设置回调函数
return e.create();
}
@Override
public Object intercept(Object obj, Method m, Object[] args, MethodProxy pro) throws Throwable {
return m.invoke(target, args);//执行目标对象的方法
}
}
使用:类名 对象名 = (类名)new ProxyFactory(new 类名()).getProxyInstance();