原文地址:https://www.cnblogs.com/gonjan-blog/p/6685611.html 。写的很好
public interface Person { public void giveMoney(); } public class Student implements Person { private String name; public Student(String name) { this.name = name; } @Override public void giveMoney() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(name + "上交50元"); } } public class StuInvocationHandler<T> implements InvocationHandler { // InvocationHanlder 持有被代理对象 T target; public StuInvocationHandler(T target) { this.target = target; } /** * 可以在此方法中执行被代理类的方法,Spring中的AOP原理 * @param proxy 代表动态代理对象 * @param method 代表正在执行的方法 * @param args 代表调用目标方法时出入的实参 * @return * @throws Throwable */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("代理执行" +method.getName() + "方法"); // 这里用到反射技术 Object result = method.invoke(target, args); return result; } } public class Main { public static void main(String[] args) { // 被代理的对象 Person zhangsan = new Student("张三"); // InvocationHandler stuHandler = new StuInvocationHandler<>(zhangsan); // 代理对象 Person stuProxy = (Person)Proxy.newProxyInstance(Person.class.getClassLoader(), new Class[]{Person.class}, stuHandler); stuProxy.giveMoney(); } }