这两天对java的动态代理感兴趣,自己写了个最简单的代码,认识一下动态代理!
例子:
类列表:
MyObjec是执行类。
MyProxy 是我自己实现的动态代理类,这个类实现了InvocationHandler接口,关于这个借口的描述就不多说了,可以参照api文档!好像动态代理类都实现这个接口,我是这么理解的,呵呵!
Test 类是我的业务类
ITest 是我业务类的接口!
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- public class MyObject {
- public static void main(String[] args) {
- ITest test = new Test("kimi");
- ITest t = new MyProxy().getProxy(test);
- t.outPut();
- }
- }
- class MyProxy implements InvocationHandler {
- private ITest itest = null;
- private Object test = null;
- public synchronized ITest getProxy(Object o) {//用Factory的方式取代理实例,不知道做得对不对
- if (itest == null) {
- test = o;
- itest = (ITest) Proxy.newProxyInstance(
- this.getClass().getClassLoader(),
- o.getClass().getInterfaces(),
- this);
- return itest;
- } else
- return itest;
- }
- public Object invoke(Object o, Method m, Object[] aguments) throws Throwable {
- System.out.println("my Proxy start ok!!!");
- return m.invoke(
- test,
- aguments);
- }
- }
- class Test implements ITest {
- private String name = null;
- public Test(String name) {
- this.name = name;
- }
- public void outPut() {
- System.out.println("my Test start ok!!!" + String.format("%n") + "my name is :" + this.name);
- }
- }
- interface ITest {
- public void outPut();
- }
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class MyObject { public static void main(String[] args) { ITest test = new Test("kimi"); ITest t = new MyProxy().getProxy(test); t.outPut(); } } class MyProxy implements InvocationHandler { private ITest itest = null; private Object test = null; public synchronized ITest getProxy(Object o) {//用Factory的方式取代理实例,不知道做得对不对 if (itest == null) { test = o; itest = (ITest) Proxy.newProxyInstance( this.getClass().getClassLoader(), o.getClass().getInterfaces(), this); return itest; } else return itest; } public Object invoke(Object o, Method m, Object[] aguments) throws Throwable { System.out.println("my Proxy start ok!!!"); return m.invoke( test, aguments); } } class Test implements ITest { private String name = null; public Test(String name) { this.name = name; } public void outPut() { System.out.println("my Test start ok!!!" + String.format("%n") + "my name is :" + this.name); } } interface ITest { public void outPut(); }
- 最后,如有不妥当之处,请指示~!谢谢
最后,如有不妥当之处,请指示~!谢谢