Cglib代理

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
26
27
28
29
30
31
32
33
34
35
//被代理类
public class PersonService {
public void eat(){
System.out.println("吃饭");
}
}

//代理类
public class Cglib implements MethodInterceptor{

private Enhancer enhancer = new Enhancer();

public Object getProxy(Class clazz){
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create();
}

@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("拿筷子" + method);
Object invoke = methodProxy.invokeSuper(o, objects);
System.out.println("洗碗" + method);
return invoke;
}
}
//main
public class Main {

public static void main(String[] args) {
Cglib ct = new Cglib();
PersonService proxy = (PersonService) ct.getProxy(PersonService.class);
proxy.eat();
}
}
Donate comment here