1、写一个接口
public interface BuyPhoneService { void buyPhone(String phone); }
2、实现接口
public class BuyPhoneServiceImpl implements BuyPhoneService { @Override public void buyPhone(String phone) { System.out.println("买"+ phone +"手机"); } }
3、编写匿名内部类并调用
public class Xc { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { BuyPhoneService buyPhoneService = new BuyPhoneServiceImpl(); BuyPhoneService aa = (BuyPhoneService) Proxy.newProxyInstance(buyPhoneService.getClass().getClassLoader(), buyPhoneService.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("增强"); Object invoke = method.invoke(buyPhoneService, "华为"); System.out.println("增强"); return invoke; } }); aa.buyPhone("小米"); } }