动态代理小模拟总是找不到错误!小菜···
document 一:
public interface Subject {
public void doAction();
}
document 二:
import com.staticproxy.Subject;
public class RealSubject implements Subject {
@Override
public void doAction() {
System.out.println("From RealSubject!");
}
}
document 三:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyProxy implements InvocationHandler {
private Object object;
public MyProxy(Object object) {
super();
this.object = object;
}
//通过动态代理,将调用方法转给 InvocationHandler 类型的 handler.
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
this.before();
method.invoke(object, args);
this.after();
return null;
}
private void before() { //额外增加的
System.out.println("Before doing");
}
private void after() { //额外增加的.
System.out.println("After doing");
}
}
document 四:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Client {
public static void main(String[] args) throws Exception {
RealSubject realSubject = new RealSubject(); // 真实角色.
InvocationHandler handler = new MyProxy(realSubject);
// 为了生成 DynamicProxy.
Class<?> classType = handler.getClass();
// 下面的代码一次性生成代理
Subject subject = (Subject) Proxy.newProxyInstance(classType
.getClassLoader(), realSubject.getClass().getInterfaces(),
handler);
subject.doAction();
}
}
为什么总是 :
Exception in thread "main"
java.lang.ClassCastException: $Proxy0 cannot be cast to com.dynamicproxy.Subject
找不到哪里错,应该是对的,崩溃。
------解决方案--------------------
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyProxy implements InvocationHandler {
private Object object;
public MyProxy(Object object) {
super();
this.object = object;
}
//通过动态代理,将调用方法转给 InvocationHandler 类型的 handler.
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
this.before();
method.invoke(object, args);
this.after();
return null;
}
private void before() { //额外增加的
System.out.println("Before doing");
}
private void after() { //额外增加的.
System.out.println("After doing");
}
}
这一部分首先有问题,大概应该这样:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyProxy implements InvocationHandler {
//通过动态代理,将调用方法转给 InvocationHandler 类型的 handler.
@Override
public Object invoke(Object proxy, Method method, Object[] args)