java有关静态代理及动态代理的实现
Posted 盗帅_tim
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java有关静态代理及动态代理的实现相关的知识,希望对你有一定的参考价值。
public interface MyInterface { void doSomeThing(); void someThingElse(String param); }
public class RealObject implements MyInterface{ @Override public void doSomeThing() { // TODO Auto-generated method stub print("开始调用doSomeThing方法"); } @Override public void someThingElse(String param) { // TODO Auto-generated method stub print("开始调用somethingelse 方法;参数"+param); } }
public class SimpleProxy implements MyInterface{ private MyInterface myInterface; public SimpleProxy(MyInterface myInterface) { this.myInterface=myInterface; } @Override public void doSomeThing() { // TODO Auto-generated method stub print("业务逻辑dosomething..."); myInterface.doSomeThing(); } @Override public void someThingElse(String param) { // TODO Auto-generated method stub print("业务逻辑ELse..."); myInterface.someThingElse(param); } public static void consumer(MyInterface myInterface) { myInterface.doSomeThing(); myInterface.someThingElse("bubu.."); } public static void main(String[] args) { consumer(new RealObject()); consumer(new SimpleProxy(new RealObject())); } }
以下是动态代理
自定义一个调用处理器:
/** * 调用处理器<P> * 动态代理能把所有调用都重定向到调用处理器上 */ public class DynamicProxyHandle implements InvocationHandler{ private Object proxied; public DynamicProxyHandle(Object object) { this.proxied=object; } @Override public Object invoke(Object proxy,Method method,Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { print("proxy class:"+proxy.getClass()+" method:"+method+" args:"+args); if(method.getName().equals("doSomeThing")) { print("代理检测到doSomeThing被调用"); } // if(args!=null) { // for(Object object:args) { // print("====="+object); // } // } return method.invoke(proxied, args); } }
public class SimpleDynamicProxy { public static void consumer(MyInterface myInterface) { myInterface.doSomeThing(); myInterface.someThingElse("bubu.."); } public static void main(String[] args) { RealObject realObject = new RealObject(); consumer(realObject); print("-----------------------------------------"); /** * 1.一个类加载器【你通常可以从已经被加载的类对象中获取得到其类加载器,然后传递给它】 * 2.希望该代理实现的接口列表【不是类或抽象类】 * 3.以及InvocationHandler的一个实现(一个调用处理器) */ MyInterface dynamicProxy = (MyInterface) Proxy.newProxyInstance(MyInterface.class.getClassLoader(), new Class[]{MyInterface.class}, new DynamicProxyHandle(realObject)); consumer(dynamicProxy); } }
以上是关于java有关静态代理及动态代理的实现的主要内容,如果未能解决你的问题,请参考以下文章