- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicProxyTest.java
More file actions
Latest commit
55 lines (43 loc) · 1.56 KB
/
Copy pathDynamicProxyTest.java
File metadata and controls
55 lines (43 loc) · 1.56 KB
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
packageJavaPatternDemos;
importjava.lang.reflect.InvocationHandler;
importjava.lang.reflect.Method;
importjava.lang.reflect.Proxy;
/**
* 动态代理,使用java提供的Proxy对象
*/
publicclassDynamicProxyTest {
publicstaticvoidmain(String[] args) throwsException{
MyProxyImplpObj = newMyProxyImpl();
MyInvokeHandlermyHandlder = newMyInvokeHandler(pObj);
ProxyInterfaceproxyProduced = (ProxyInterface) Proxy.newProxyInstance(
ProxyInterface.class.getClassLoader(),
newClass<?>[]{ProxyInterface.class},
myHandlder);
System.out.println(proxyProduced.updateName("Badass"));
}
}
interfaceProxyInterface {
StringupdateName(Stringname_);
}
classMyProxyImplimplementsProxyInterface {
privateStringname = "default";
publicStringupdateName(StringnewName){
System.out.println(name);
name = newName;
returnnewName;
}
}
classMyInvokeHandlerimplementsInvocationHandler{
privateObjecttarget = null; //这里可以只针对ProxyInterface对象
publicMyInvokeHandler(ObjectaTarget){
target = aTarget;
}
@Override
publicObjectinvoke(Objectproxy, Methodmethod, Object[] args) throwsThrowable {
// 这里的proxy实际上是生成的代理对象,见下面的Name,是$proxy0
System.out.println("this is from a handler");
System.out.println(proxy.getClass().getName());
Objectresult = method.invoke(target,args);
returnresult;
}
}