import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyTest { public static void main(String[] args) { Target target = (Target)Proxy.newProxyInstance(TargetImpl.class.getClassLoader(), TargetImpl.class.getInterfaces(), new MyInterceptor()); target.say(); /* Console: 拦截之前 this is Target.class 拦截之后 */ } } //目标类接口 interface Target { void say(); } //目标类 class TargetImpl implements Target { @Override public void say() { System.out.println("this is Target.class"); } } //拦截器 class MyInterceptor implements InvocationHandler { private Object target = new TargetImpl(); @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("拦截之前"); method.invoke(target, args);//调用目标类方法 System.out.println("拦截之后"); return null; } }
时间: 2024-11-08 09:03:40