62,612
社区成员
发帖
与我相关
我的任务
分享
public interface Subject
{
public boolean request();
}
这是抽象角色的公共接口
public class RealSubject implements Subject
{
public boolean request()
{
boolean b = false;
System.out.println(b);
return b;
}
}
这是具体角色,被代理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicProxy implements InvocationHandler
{
Object obj;
public DynamicProxy(Object obj)
{
this.obj = obj;
}
public Object invoke(Object proxy, Method method, Object[] args)throws Throwable
{
System.out.println("before proxy:" + method);
Object object = method.invoke(obj, args);
//method.invoke(obj,args);
System.out.println("after proxy:" + method);
return object;
//return null;
}
}
这是代理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Client
{
public static void main(String[] args)
{
RealSubject real = new RealSubject();
InvocationHandler handler = new DynamicProxy(real);
Class<?> classType = handler.getClass();
Subject sub = (Subject)Proxy.newProxyInstance(classType.getClassLoader(), real.getClass().getInterfaces()
, handler);
sub.request(); }
}
这是测试类
//return null;
你返回null了啊,他要对结果进一步处理的,比如强转为你定义的返回类型,这时候就会报错啊
你返回void,就不需要进一步处理,那就不会报错了。。。
这个应该是显而易见的吧