电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

Simple-level Dynamic Proxy(1)


发布日期:2023/5/18
 

package poxy;

import javalangreflectInvocationHandler;

import javalangreflectMethod;

import javalangreflectProxy;

/**

* Simple Dynamic Proxy show a single interface a single instance case

*

* @author daniel zhou

*/

public class SimpleDynamicProxy {

/**

* @param args

*/

public static void main(String[] args) {

//generate a hanlder

ProxyHanlder hanlder=new ProxyHanlder();

/*

* register instance to hanlder get the interfaces proxy

*/

Dog dogProxy=(Dog) hanldergenerateProxyHanlder(new Dog(){

@Override

public String eat(String food) {

return Daniels dog just ate an + food +!;

}

});

//do method by proxy

String result = dogProxyeat(big bone);

//take a look

Systemoutprintln(result);

}

}

//Proxy Handler

class ProxyHanlder implements InvocationHandler{

//container

Object obj = new Object();

public Object generateProxyHanlder(Object obj) {

//store it

thisobj = obj;

//return interface proxy

return ProxynewProxyInstance(objgetClass()getClassLoader()

objgetClass()getInterfaces()

this);

}

@Override

public Object invoke(Object proxy Method method Object[] args)

throws Throwable {

Object result=null;

result=methodinvoke(obj args);

return result;

}

}

//interface

interface Dog{

String eat(String food);

}

本文出自 专注JEE系列规范下的开源技术 博客请务必保留此出处

上一篇:使用Decorator模式添加功能

下一篇:追逐代码质量: 决心采用 FIT