码迷,mamicode.com
首页 > 编程语言 > 详细

初探java的Proxy+InvocationHandler

时间:2016-02-15 16:06:16      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

reference:http://m.oschina.net/blog/224931

English page:https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html

 1 public interface Colorable {
 2 
 3     public void value();
 4     
 5 }
 6 
 7 public class RedColor implements Colorable {
 8 
 9     @Override
10     public void value() {
11         System.out.println("--------------red-------------");
12     }
13 
14 }
15 
16 public class ColorableProxy implements InvocationHandler {
17 
18     private Colorable colorable;
19     private Colorable proxy;
20     
21     public ColorableProxy(Colorable colorable) {
22         this.colorable = colorable;
23         this.proxy = (Colorable)Proxy.newProxyInstance(Colorable.class.getClassLoader(), new Class<?>[] { Colorable.class }, this);
24     }
25     
26     public Colorable getProxy() {
27         return proxy;
28     }
29     
30     @Override
31     public Object invoke(Object proxy, Method method, Object[] args)
32             throws Throwable {
33         String methodName = method.getName();
34 
35         System.out.println("===========starting invoke function:" + methodName + "==========");
36         
37         Object result = method.invoke(colorable, args);
38         
39         System.out.println("=========== invoke function:" + methodName + " success==========");
40         return result;
41     }
42 
43 }
44 
45 public class Main {
46 
47     public static void main(String[] args) {
48         
49         Colorable proxy = new ColorableProxy(new RedColor()).getProxy();
50         proxy.value();
51     }
52 
53 }

 

初探java的Proxy+InvocationHandler

标签:

原文地址:http://www.cnblogs.com/mabaishui/p/5190487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!