初探java的Proxy+InvocationHandler

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了初探java的Proxy+InvocationHandler相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

[原创]Sharding-Sphere之Proxy初探

HarmonyOS初探03——DevEco Studio创建应用问题ERROR Unable to tunnel through proxy. Proxy returns HTTP1.1 403

初探 Vue3.0 中的一大亮点——Proxy !

笔记-站点初探

JavaScipt设计模式初探-代理模式

Nginx作为动静分离缓存与负载均衡初探