首先创建一个接口,里面有一个基本的需求
接着创建一个实现类,重写这个需求
创建一个动态代理类,
1.里面new一个InvocationHandler,重写里面的invoke方法;
2.获取实现类的class对象中的具体方法;
3.在invoke方法中调用实现类方法,之后添加增强的方法;
4.根据Proxy方法中的newProxyInstance的方法获取接口的代理对象;
5.代理对象代理接口之后,获取接口里面的方法来实现增强的效果
代码实现
被代理对象接口
public interface Student { void Action(); }
被代理接口
public class StudentImpl implements Student{ public void Action() { System.out.println("hello wrold!!!"); } }
主体代码
public class MyTest { @Test public void Test() throws NoSuchMethodException { // 类加载器,通常指定被代理类的接口的类加载器 ClassLoader classLoader = Student.class.getClassLoader(); // 类型,通常指定被代理类的接口类型 Class<?>[] interfaces = Student.class.getInterfaces(); // 实例化一个被代理的对象 final StudentImpl studentImpl = new StudentImpl(); // 指定要执行代理对象方法(需要一场处理) final Method methodAction = StudentImpl.class.getMethod("Action",null); // 委托执行的处理类 InvocationHandler handler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // student为被代理对象实例化的一个对象,null为方法值 methodAction.invoke(studentImpl,null); System.out.println("我是一个增强的方法"); return null; } }; // 创建一个代理对象 Proxy proxy = (Proxy) Proxy.newProxyInstance(classLoader,interfaces,handler); // 通过代理对象实现方法的增强 System.out.println(proxy); } }
结果展示
hello wrold!!!
我是一个增强的方法
null