动态代理

基于接口动态代理 :Proxy

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
36

//接口:
public interface Sports {
public void paly();
}

//接口实现类
public class Basketball implements Sports{
@Override
public void paly() {
System.out.println("打篮球");
}
}

public class Client_Main {
public static void main(String[] args) {
final Sports sports = new Basketball();
Sports sports_Porxy = (Sports) Proxy.newProxyInstance(sports.getClass().getClassLoader(), sports.getClass().getInterfaces(), new InvocationHandler() {
/**  
* @param proxy 指代我们所代理的那个真实对象
* @param method 指代的是我们所要调用真实对象的某个方法的Method对象
* @param args 指代的是调用真实对象某个方法时接受的参数
* @return
* @throws Throwable
*/

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("先开始准备运动");
Object obj = method.invoke(sports, args);
return obj;
}
});

sports_Porxy.paly();
}
}
  • 输出:
    先开始准备运动
    打篮球

基于类的动态代理 :CGLIB

  • 前提:
    1. 被代理类不能被final修饰
    2. 必须是public

先要加入CGLIB架包:

1
2
3
4
5
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.4</version>
</dependency>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//类
public class FootBall {
public void play(){
System.out.println("踢足球");
}
}

public class Client_Main_cglib {
public static void main(String[] args) {
final FootBall footBall = new FootBall();

FootBall footBall_Proxy = (FootBall) Enhancer.create(footBall.getClass(), new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("先开始准备运动");
Object obj= method.invoke(footBall,objects);
return obj;
}
});

footBall_Proxy.play();
}
}
  • 输出:
    先开始准备运动
    踢足球