Subject pro = (Subject)Proxy.newProxyInstance(classType.getClassLoader(),realSubject.getClass().getInterfaces(),handler);
这行代码返回的到底是个什么?就是Subject类型?还是强制转换了?为什么执行
pro.request();之后会调用DynamicSubject类里面的那个method.invoke方法
public interface Subject
{
public void request();
}
public class RealSubject implements Subject
{
public void request()
{
System.out.println("From real subject");
}
}
public class DynamicSubject implements InvocationHandler
{
private Object sub;
public DynamicSubject(Object sub)
{
this.sub = sub;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
method.invoke(sub,args);
return null;
}
}
public class Client
{
public static void main(String[] args)
{
RealSubject realSubject = new RealSubject();
InvocationHandler handler = new DynamicSubject(realSubject);
Class<?> classType = handler.getClass();
Subject pro = (Subject)Proxy.newProxyInstance(classType.getClassLoader(),
realSubject.getClass().getInterfaces(),handler);
pro.request();
}
}
|
|