JDK版本1.8.
List-1
public interface Subject {
void prePrint();
void print();
void postPrint();
}
List-2
public class HelloWorldSubject implements Subject {
@Override
public void prePrint() {
System.out.println("pre");
}
@Override
public void print() {
prePrint();
System.out.println("Hello world");
postPrint();
}
@Override
public void postPrint() {
System.out.println("post");
}
}
List-3
public class JdbcDynamicalProxy implements InvocationHandler {
private Subject subject;
public JdbcDynamicalProxy(Subject subject) {
this.subject = subject;
}
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
System.out.println(method.getName()+" 前");
Object result = method.invoke(subject, objects);
System.out.println(method.getName()+" 后");
return result;
}
}
来测试下,如下List-5是结果,我们在调用print后,print方法中调用了pre/postPrint方法,但是JDK的动态代理只是拦截了print方法并执行了拦截方法,但是pre/post方法的执行前后就不会执行,这也是为什么spring中有时候事务传播会失效、调用标有@AsynTask注解的方法——想用异步方式执行会失效的原因。
List-4
public class DynamicTest {
@Test
public void test(){
HelloWorldSubject subject = new HelloWorldSubject();
Subject instance = (Subject) Proxy.newProxyInstance(this.getClass().getClassLoader(), HelloWorldSubject.class.getInterfaces(), new JdbcDynamicalProxy(subject));
instance.print();
}
}
List-5
print 前
pre
Hello world
post
print后