代理
代理目前大致有以下几种:
- JDK动态代理 基于接口
- CGLib 动态生成子类
- Javassist
- Byte buddy
前两种是在spring中用的
JDK动态代理
代码语言:java复制public class ProxyTest {
public interface F
{
public void say();
}
public interface O
{
public void sayOther();
}
@Test
public void jdkTest() {
Object obj = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {F.class,O.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
F f = new F() {
@Override
public void say() {
System.out.println("say F");
}
};
if(method.getName().equals("say")) {
}
System.out.println("say P");
f.say();
return null;
}
});
F f = (F)obj;
f.say();
}
}
动态代理生成的对象继承Proxy,并实现了目标接口
CGLIB
CGLIB 通过ASM方法,加载并更改字节码,生成目标类的子类。
代码语言:java复制// 注意不能放在但愿你测试类中,否则会报错
// Superclass has no null constructors but no arguments were given
public class FD {
public void say() {
System.out.println("");
}
}
@Test
public void cglibTest() {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(FD.class);
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object source, Method method, Object[] args,MethodProxy methodProxy) throws Throwable
{
System.out.println("say Cglib");
Object result = methodProxy.invokeSuper(source, args);
return result;
}
});
///
FD f = (FD) enhancer.create();//new Class[] {this.getClass()}, new Object[] {this});//create();
f.say();
}