动态代理

2017-01-02  本文已影响24人  youngYmca

动态代理主要用来做方法的增强,可以让你在不修改源码的情况下,可以在方法执行前插入一些公共方法,或者在方法执行后插入一些公共方法(AOP)。如果方法比较多,且方法具有相似性的情况下,可以只定义接口,通过动态代理来实现接口,极大的减少代码量。实现无侵入式的代码扩展。

首先定义一个接口:

public interface TestInterface {
    void test(String str);
}

实现该接口:

public class TestImplement implements TestInterface {
    @Override
    public void test(String str) {
        System.out.println(str);
    }
}

动态代理类:

public class TestProxy implements InvocationHandler{
    private Object obj;
    public TestProxy(Object obj){
        this.obj = obj;
    }
    public TestProxy(){}
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        //do something before
        result = method.invoke(obj, args);//调用实例方法。
        //do something after
        return result;
    }
}

动态代理测试:

public static void main(String[] args) {
        TestInterface i = new TestImplement();//获取被代理类
        TestProxy proxy = new TestProxy(i);//动态代理类
        Class<?> clazz = i.getClass();
        TestInterface t = (TestInterface)Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), proxy);
        t.test("xx");
    }

上面的t是生成出来的动态代理实例,是Proxy的一个实例$Proxy0该实例实现了TestInterface接口。故当调用test()方法的时候就会走到TestProxy.invoke方法。可以在TestProxy中自定义业务逻辑。实现无侵入式代码扩展。当然也可以不需要TestImplement实现类,只需要在invoke方法中根据参数来自定义实现。所以就会有一些框架代码看起来比较神奇,比如RetrofitMybatis等只需要定义接口。不需要对接口进行实现。

Retrofit

概念

一个类型安全的HTTP客户端,是注解形式的封装库。是一个基于OkHttp的包装库,使用简单,只需要定义接口加上注解即可。

使用方法

引用retrofit、gson依赖,gson用来将json数据转换为object

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

然后自定义接口用来获取想要的数据。在接口上以注解或者参数的方式将远程API接口所需要的参数配置上去。
再用Retrofit.create出接口的实例即可使用。源码如下:

public <T> T create(final Class<T> service) {
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
        new InvocationHandler() {
          private final Platform platform = Platform.get();

          @Override public Object invoke(Object proxy, Method method, Object... args)
              throws Throwable {
            // If the method is a method from Object then defer to normal invocation.
            if (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            ServiceMethod<Object, Object> serviceMethod =
                (ServiceMethod<Object, Object>) loadServiceMethod(method);
            OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
  }

这里使用了动态代理机制。可以看出在实现InvocationHandler里面,解析了method中的注解,和参数。拼成OkHttp参数请求发送再返回。

Mybatis

跟retrofit很相似,mybatis也是利用动态代理,用户只需要定义接口即可。利用参数和注解生成sql。不同的时mybatis的接口方法命名决定了sql执行命令CRUD。

MapperProxy的invoke方法如下:

@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

在MapperProxyFactory中获取代理类。

protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

跟retrofit基本一样,两者都使用了cached,将接口的实例缓存起来。

一句话总结

动态代理是为其他对象提供一种代理以控制这个对象的方法。

上一篇 下一篇

猜你喜欢

热点阅读