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(); }
}这是测试类
假如运行代理类中被注释掉的语句,在运行结束后产生NullPointerException;假如把公共接口中的那个方法返回值改为void就不会出现这样的情况,请大家帮帮忙这是什么情况。