2008-02-22
java动态代理

//===== file:DynamicProxyFactory.java =====

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

public class DynamicProxyFactory {
/**
* 创建代理对象
* @param target : 必须实现某个接口的对象
* @return 代理对象
*/
public static Object newProxyInstance(final Object target) {
Object proxy = Proxy.newProxyInstance(target.getClass()
.getClassLoader(), target.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
System.out.println("before invoke");
Object returnValue = method.invoke(target, args);
System.out.println("after invoke");
return returnValue;
}
});
return proxy;
}
}

//===== file:IProxy.java =====
public interface IProxy {
public String invoke();
}

//===== file:ProxyObject.java =====

public class ProxyObject implements IProxy {
public String invoke() {
System.out.println("method invoke");
return "oldobject";
}
}

//===== file:Test.java =====
public class Test {
public static void main(String[] args) {
ProxyObject oldobject = new ProxyObject();
IProxy newobject = (IProxy) DynamicProxyFactory.newProxyInstance(oldobject);
System.out.println(newobject.invoke());

}
}
发表评论
- 浏览: 4210 次
- 性别:

- 来自: 上海

- 详细资料
搜索本博客
最新评论
-
websphere5.1+spring2.0+s ...
如果确定文件在的话,按上述步骤试下,6.1没用过,看是否是相同的原因,希望你成功 ...
-- by hrtc -
websphere5.1+spring2.0+s ...
我项目在工作的时候由于方便,所以就在tomcat5.5下运行 上线的时候客户要求 ...
-- by yuyang030405 -
websphere5.1+spring2.0+s ...
Good practical article! Thanks for shar ...
-- by xzcgeorge -
java servletfilter实现全 ...
另外生成是用另一线程做的,所以不会影响当前请求。
-- by hrtc -
java servletfilter实现全 ...
看你的页面访问率决定如何设置了,比如说生成时间设成1分钟,那么1分钟里只会生成1 ...
-- by hrtc







评论排行榜