文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>java.lang.reflect.Proxy例子

java.lang.reflect.Proxy例子

时间:2010-04-07  来源:qbq

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface AnInterface {
    public void doSth();
}

interface AnotherInterface {
    public void anotherdo();
}

class AClass implements AnInterface, AnotherInterface {
    public void doSth() {
        System.out.println("inside AClass.doSth");
    }

    public void anotherdo() {
        System.out.println("inside AClass.anotherdo");
    }
}

class SimpleInvocationHandler implements InvocationHandler {
    private Object realObject;

    public SimpleInvocationHandler(Object realObject) {
        this.realObject = realObject;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        System.out.println("Before calling: " + method.getName());
        result = method.invoke(realObject, args);
        System.out.println("After calling: " + method.getName());
        System.out.println(proxy.getClass().getName());
        return result;
    }
}

public class ProxyTest {
    public static void main(String[] args) {
        AnInterface realSubject = new AClass();
        AnInterface anProxy = (AnInterface) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), new Class[] { AnInterface.class },
                new SimpleInvocationHandler(realSubject));

        anProxy.doSth();
        System.out.println(Proxy.isProxyClass(anProxy.getClass()));
        System.out.println(anProxy instanceof AnInterface);

        AnotherInterface anotherProxy = (AnotherInterface) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(),
                new Class[] { AnotherInterface.class }, new SimpleInvocationHandler(realSubject));

        anotherProxy.anotherdo();
        System.out.println(Proxy.isProxyClass(anotherProxy.getClass()));
        System.out.println(anotherProxy instanceof AnotherInterface);

    }
}


相关阅读 更多 +
排行榜 更多 +
开心动动脑安卓版 v1.0 手机版

开心动动脑安卓版 v1.0 手机版

休闲益智 下载
不良人破局手游下载

不良人破局手游下载

角色扮演 下载
云海之下手游下载

云海之下手游下载

角色扮演 下载