首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java 署理,InvocationHandler,Proxy

2012-10-26 
Java 代理,InvocationHandler,Proxypublic class Test {??? public static void main(String[] args) {???

Java 代理,InvocationHandler,Proxy

public class Test {

??? public static void main(String[] args) {
??? ??? // TODO Auto-generated method stub

??? ??? Test t=new Test();

? ? ?? ? t.inter();
??? }

?? void inter(){
??? ??? ServiceProxy proxy = new ServiceProxy();
??? ??? ServiceImpl service = new ServiceImpl();
??? ??? proxy.setService(service);
??? ??? Object service2 = Proxy.newProxyInstance(ServiceImpl.class.getClassLoader(), new Class[]{Service.class}, proxy);
??? ??? System.out.println(service2.getClass());
??? ??? Service s = (Service)service2;???????????? //只能转换为接口
??? }

}

?

interface Service{
??? String prt();
}

class ServiceImpl implements Service{
??? public String prt(){
??? ??? System.out.println(" Interface Impl");
??? ??? return "InterFaceImpl";
??? }
}

class ServiceProxy implements InvocationHandler{

??? Object service;
???
??? void setService(Object service){
??? ??? this.service=service;
??? }
??? public Object invoke(Object proxy, Method method, Object[] args)
??? ??? ??? throws Throwable {
??? ??? Object o=null;
??? ??? o=method.invoke(service, args);
??? ??? return o;
??? }
}

热点排行