动态代理

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
动态代理:不改变源码的情况下对源码进行增强。

* @author lilair
* @create 2019-08-29 10:18
*/
public interface {
void dangerAct(double money);
void basicAct(double money);
}


* @author lilair
* @create 2019/08/29 10:19
*/
public class Actor implements {


public void dangerAct(double money) {
System.out.println("危险的表演需要"+money);
}


public void basicAct(double money) {
System.out.println("基础的表演需要"+money);
}
}



* @author lilair
* @create 2019/08/29 10:22
*/
public class test {
public static void main(String[] args) {
Actor actor= new Actor();
IActor proxyActor = (IActor) Proxy.newProxyInstance(Actor.class.getClassLoader(), Actor.class.getInterfaces(), new InvocationHandler() {

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
IActor retValue=null;
String name=method.getName();
Double money= (Double) args[0];
if ("dangerAct".equals(name)){
if(money>1000){
method.invoke(actor,money/2);
}
}
if ("basicAct".equals(name)){
if(money>2000){
method.invoke(actor,money/2);
}
}
return retValue;
}
});
proxyActor.basicAct(10000);
proxyActor.dangerAct(20000);
}

}