文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
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);

    }
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载