首页 > 其他 > 详细

java动态代理

时间:2014-02-20 15:56:43      阅读:280      评论:0      收藏:0      [点我收藏+]

1、接口

public interface Foo {
    void modify();
    void ff(int x);
}

2、被代理类

public class FooImpl implements Foo {
@Override
public void modify() {
   System.out.println("*******modify()方法被调用");
}
@Override
public void ff(int x) {
    System.out.println("ff()方法被调用啦啊啊啊啊啊啊啊");
               
}
}

3、动态代理类

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler {
    private Object o=null;
    public MyInvocationHandler(Object o){
        this.o=o;
    }
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println(method.getName()+"被调用,参数:"+args[0].toString());
         Object ret = method.invoke(this.o, args);
        System.out.println(method.getName()+"调用结束");
        return ret;
    }
}

4、测试程序及结果

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
public class ProxyClass {
    public static void main(String arags[]) throws IllegalArgumentException,
            SecurityException, InstantiationException, IllegalAccessException,
            InvocationTargetException, NoSuchMethodException {
        InvocationHandler handler = new MyInvocationHandler(new FooImpl());
             
        Class proxyClass = Proxy.getProxyClass(Foo.class.getClassLoader(),
                new Class[] { Foo.class });
        Foo f = (Foo) proxyClass.getConstructor(
                new Class[] { InvocationHandler.class }).newInstance(
                new Object[] { handler });
        //f.modify();
        f.ff(2211);
    }
}


bubuko.com,布布扣

java动态代理

原文:http://5070780.blog.51cto.com/5060780/1360500

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!