动态代理小模拟总是找不到错误!小菜···
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)
throws Throwable {
this.before();
Object result = method.invoke(proxy, args);
this.after();
return result;
}
private void before() { //额外增加的
System.out.println("Before doing");
}
private void after() { //额外增加的.
System.out.println("After doing");
}
}
Subject subject = (Subject) Proxy.newProxyInstance(classType
.getClassLoader(), realSubject.getClass().getInterfaces(),
handler);
Subject subject = (Subject) Proxy.newProxyInstance(
realSubject.getClass().getClassLoader(),
new Class<?>[]{ Subject.class },
new MyProxy()
);
public interface Subject {
public void doAction();
}
public class RealSubject implements Subject {
@Override
public void doAction() {
System.out.println("From RealSubject!");
}
}
public class MyProxy implements InvocationHandler {
private Object o;
MyProxy(Object o) {
this.o = o;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
before();
Object result = method.invoke(o, args);
after();
return result;
}
private void before() {
System.out.println("Before doing");
}
private void after() {
System.out.println("After doing");
}
}
public class Client {
public static void main(String[] args) throws Exception {
RealSubject realSubject = new RealSubject();
Subject subject = (Subject)Proxy.newProxyInstance(
realSubject.getClass().getClassLoader(),
new Class<?>[]{ Subject.class },
new MyProxy(realSubject)
);
subject.doAction();
}
}