1.代理的书写,是比较麻烦的,写原生代理,又是一件无聊且容易遗漏的事情。写了一个简单的代理类,可借鉴也可指出错误。
1 package cn; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 import java.lang.reflect.Proxy; 6 7 /** 8 * 代理类的基础,必须先是设置对象(必须是接口对象赋值实现类),不然获取的代理对象会空指针。 9 * @author jxlys 10 * 11 */ 12 public class Proxy implements InvocationHandler { 13 private obj; 14 15 public Proxy () { 16 } 17 18 public Proxy ( obj) { 19 this.obj = obj; 20 } 21 22 public getObj() { 23 return obj; 24 } 25 26 public void setObj( obj) { 27 this.obj = obj; 28 } 29 30 /** 31 * 获得代理对象 32 * 33 * @param t 34 * @return 35 */ 36 public <T> T getProxy(Class<T> t) { 37 return get (t, getProxy()); 38 } 39 40 /** 41 * 获得代理对象 42 */ 43 public getProxy() { 44 return obj != null ? Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this) : null; 45 } 46 47 // 对象强转 48 @SuppressWarnings("unchecked") 49 public <T> T get (Class<T> t, obj) { 50 return obj != null ? (T) obj : null; 51 } 52 53 public void beforeAction() { 54 } 55 56 public void afterAction() { 57 } 58 59 public invoke( proxy, Method method, [] args) throws Throwable { 60 beforeAction(); 61 invoke = method.invoke(obj, args); 62 afterAction(); 63 return invoke; 64 } 65 }
调用如下:
1 interface A { 2 public void say(); 3 } 4 5 class B implements A { 6 7 public void say() { 8 System.out.print("love"); 9 } 10 } 11 12 public class TestMain { 13 14 public static void main(String[] args) { 15 A a = new B(); 16 a.say();//未代理17 Proxy pbu = new Proxy (a) { 18 public void beforeAction() { 19 System.out.print("I "); 20 } 21 22 public void afterAction() { 23 A a = get (A.class, getObj()); 24 System.out.print(" You!"); 25 } 26 }; 27 a = pbu.getProxy(A.class); 28 pbu = null;//这一步不重要,也可以没有。 29 a.say();// 已代理,也可以用继承的方式实现代理。 30 } 31 }
继续阅读与本文标签相同的文章
-
Python快递鸟API接口对接(即时查询|物流跟踪|电子面单|单号识别)
2026-05-18栏目: 教程
-
免费物流快递单号查询API接口及使用教程
2026-05-18栏目: 教程
-
【译】Hadoop发生了什么?我们该如何做?
2026-05-18栏目: 教程
-
阿里云上云企业案例周刊·第2期
2026-05-18栏目: 教程
-
虚拟机模拟部署Extended Clusters(一)基础环境准备
2026-05-18栏目: 教程
