public interface Base { void baseMethod(); }
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class CustomHandler<T> implements InvocationHandler { T target; public CustomHandler(T target){ this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("start..."); Object result = method.invoke(target, args); System.out.println("end..."); return result; } }
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; public class ProxyTest { public static void main(String[] args) { Base base = () -> System.out.println("in hand..."); InvocationHandler handler = new CustomHandler<>(base);
// 生成代理对象 Base baseProxy = (Base)Proxy.newProxyInstance(ProxyTest.class.getClassLoader(), new Class[]{Base.class}, handler); baseProxy.baseMethod(); } }
start...
in hand...
end...
Process finished with exit code 0
原文:https://www.cnblogs.com/acelly/p/10432541.html