java动态代理

来源:互联网 发布:屏幕像素算法 编辑:程序博客网 时间:2024/06/10 08:52
<pre name="code" class="java">import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;interface A{public void hello();}class B implements A{public void hello(){System.out.println("********hello!这是B********");}}class B1 implements A{public void hello(){System.out.println("********hello!这是B1*******");}}class C implements InvocationHandler{Object proxyed=null;C(Object proxy){this.proxyed=proxy;}public Object invoke(Object proxy,Method m,Object[] args) throws Throwable{Object result=null;System.out.println("可以在调用具体的实现类方法前做一些其他事");result=m.invoke(proxyed, args);System.out.println("可以在调用具体的实现类方法后做一些其他事");return result;}}public class DynamicProxy {public static void main(String[] args) {B b=new B();A a=(A) Proxy.newProxyInstance(b.getClass().getClassLoader(),b.getClass().getInterfaces(), new C(new B()));a.hello();System.out.println("");A a1=(A) Proxy.newProxyInstance(b.getClass().getClassLoader(), b.getClass().getInterfaces(), new C(new B1()));a1.hello();}}


                                             
0 0
原创粉丝点击