接口 public interface Caculator { // 加法 void add(int a, int b); // 减法 void sub(int a, int b); } 目标类 public class CaculatorImpl implements Caculator{ @Override public void add(int a, int b) { System.out.println(a + b); } @Override public void sub(int a, int b) { System.out.println(a - b); } } 动态生成代理类 public class MyProxy { public static Object getProxy(Object target) { Object proxy = Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("执行了" + method.getName() + "方法"); return method.invoke(target, args); } } ); return proxy; } } 测试 public class Main { public static void main(String[] args) { Caculator caculator = new CaculatorImpl(); Caculator proxy = (Caculator) MyProxy.getProxy(caculator); proxy.add(1, 2); proxy.sub(2, 1); } }