1.创建接口
package com.liubo.test; /* * 定义接口,JDK动态代理是基于接口的 */ public interface RealInterface { public void save(); }
2.创建真实对象的类
package com.liubo.test; public class RealSubject implements RealInterface { private String name; private double money; public RealSubject(String name, double money) { this.name = name; this.money = money; } @Override public void save() { System.out.println("用户" + name + "存入了" + money + "人民币"); } }
3.创建调用器执行对象
package com.liubo.test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /* * 调用执行器 (英文直译) */ public class InvactionHandlerImpl implements InvocationHandler { private RealInterface realSubject; public InvactionHandlerImpl(RealInterface realSubject) { this.realSubject = realSubject; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("在存入钱之前你输入了密码!"); method.invoke(realSubject, args); System.out.println("在存入钱之后你取出了银行卡!"); return null; } }
4.创建Test类
package com.liubo.test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; public class Test { public static void main(String[] args) { // 创建要 代理的真实对象 RealInterface realSubject = new RealSubject("草莓大叔", 1234.5); // 创建调用执行器对象 InvocationHandler handler = new InvactionHandlerImpl(realSubject); // 获得类加载器 ClassLoader loader = Test.class.getClassLoader(); // 获得真实对象实现的接口集合 Class[] interfaces = realSubject.getClass().getInterfaces(); RealInterface proxySubject = (RealInterface) Proxy.newProxyInstance(loader, interfaces, handler); proxySubject.save(); } }
结果:
在存入钱之前你输入了密码!
用户草莓大叔存入了1234.5人民币
在存入钱之后你取出了银行卡!