接口:
package proxy;
public interface IBusiness {
void doBusiness();
}被代理类:
package proxy;
public class BusinessImpl implements IBusiness{
public void doBusiness() {
System.out.println("doBusiness()");
}}
拦截类:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;public class BusinessInterceptor implements InvocationHandler {
private IBusiness biz;
public Object invoke(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
System.out.println("before");
Object obj = arg1.invoke(biz, arg2);
System.out.println("after");
return obj;
}
public BusinessInterceptor(IBusiness biz) {
this.biz = biz;
}
}
测试类:
package proxy;import java.lang.reflect.Proxy;/*
* 静态代理
*/
public class Test {
public static void main(String[] args) {
BusinessImpl biz = new BusinessImpl();
BusinessInterceptor proxy = new BusinessInterceptor(biz);
Object bus = Proxy.newProxyInstance(biz.getClass().getClassLoader(),IBusiness.class.getInterfaces(),proxy);
System.out.println(bus instanceof BusinessImpl);
((IBusiness)bus).doBusiness();
}
}问题:
false
Exception in thread "main" java.lang.ClassCastException: $Proxy0
at proxy.Test.main(Test.java:14)怎么报异常了?????
package proxy;
public interface IBusiness {
void doBusiness();
}被代理类:
package proxy;
public class BusinessImpl implements IBusiness{
public void doBusiness() {
System.out.println("doBusiness()");
}}
拦截类:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;public class BusinessInterceptor implements InvocationHandler {
private IBusiness biz;
public Object invoke(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
System.out.println("before");
Object obj = arg1.invoke(biz, arg2);
System.out.println("after");
return obj;
}
public BusinessInterceptor(IBusiness biz) {
this.biz = biz;
}
}
测试类:
package proxy;import java.lang.reflect.Proxy;/*
* 静态代理
*/
public class Test {
public static void main(String[] args) {
BusinessImpl biz = new BusinessImpl();
BusinessInterceptor proxy = new BusinessInterceptor(biz);
Object bus = Proxy.newProxyInstance(biz.getClass().getClassLoader(),IBusiness.class.getInterfaces(),proxy);
System.out.println(bus instanceof BusinessImpl);
((IBusiness)bus).doBusiness();
}
}问题:
false
Exception in thread "main" java.lang.ClassCastException: $Proxy0
at proxy.Test.main(Test.java:14)怎么报异常了?????
解决方案 »
- 正则表达式求解,在线等。。。。。。。。。。
- Java绘图(坦克大战) 高手看看
- 高分清高手——Java开发一个用来制作chm文件的工具
- 关于 J2SE和 eclipse
- 急求tomcat 5.0.28 URL!!!!!!!!!!!!!!!
- 求教一个继承的问题
- 帮个忙,系统设置!!!
- 谁能推荐本叙述“流”比较好的书?
- "FormatFunction.java": Error #: 354 : incompatible types; found: java.lang.String, required: int at line 117, column 29 这是什么
- 关于缩略图
- 有一个文件有大量数据(几十万)条记录,内存问题暂不考虑,请问用什么数据结构和算法可以最快的查找到随机的一条记录。
- struts2 s:select 下拉列表控件如何设置为不可编辑?
这一句有问题,应该为:
Object bus = Proxy.newProxyInstance(biz.getClass().getClassLoader(),biz.getClass().getInterfaces(),proxy);