Jdk动态代理和Cglib动态代理

Jdk动态代理和Cglib动态代理

Jdk动态代理:

只能为接口实现代理

接口:

1
2
3
4
public interface IUser {

String getName(String name);
}

实现类:

1
2
3
4
5
6
public class User implements IUser {
@Override
public String getName (String name) {
return name;
}
}

实现InvocationHandler接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {
private Object target;

public MyInvocationHandler(Object target){
this.target = target;
}
@Override
public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {
System.out.print(method.getName()+"\n");
return method.invoke(target,args);
}
}

调用:

1
2
3
4
5
6
7
8
9
10
11
import java.lang.reflect.Proxy;

public class test {

public static void main(String []args){
IUser u = new User();
MyInvocationHandler invocationHandler = new MyInvocationHandler(u);
IUser proxy = (IUser) Proxy.newProxyInstance(u.getClass().getClassLoader(),u.getClass().getInterfaces(),invocationHandler);
System.out.print(proxy.getName("hello"));
}
}

cglib动态代理:

为类生成代理,被代理类无需实现接口,
引入jar包版本asm3.31对应cglib-2.2.2(对应其他版本cglib可能会有冲突,)
被代理类不能用final修饰,要生成子类

被代理类:

1
2
3
4
5
6
public class User {

public String getName(String name){
return name;
}
}

实现MethodInterceptor接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class UserCglib implements MethodInterceptor {
private Object target;

public Object getInstance(Object target){
this.target = target;
//创建加强器,用来创建动态代理类
Enhancer enhancer = new Enhancer();
//为加强器指定要代理的业务类(即:为下面生成的代理类指定父类)
enhancer.setSuperclass(this.target.getClass());
//设置回调:对于代理类上所有方法的调用,都会调用CallBack,而Callback则需要实现intercept()方法进行拦
enhancer.setCallback(this);
// 创建动态代理类对象并返回
return enhancer.create();
}
// 实现回调方法
@Override
public Object intercept (Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
return methodProxy.invokeSuper(o,objects);
}

调用:

1
2
3
4
5
6
7
8
9
public class test {

public static void main(String []args){
User user = new User();
UserCglib userCglib = new UserCglib();
User proxy = (User)userCglib.getInstance(user);
System.out.print(proxy.getName("hello"));
}
}
Thanks!