【RPC】mock模拟对象
为什么
实际开发中可能出现远程服务在维护暂时访问不了的情况出现,利用mock模拟调用真实的远程服务可以便于接口的测试、调试、开发
怎么实现
利用动态代理技术生成接口实现类的对象,并在处理器中重写相关的逻辑,返回特定的值
动态代理
根据传入的参数让JVM自动实现静态代理部分的代码,也就是动态生成了接口的实现类
- 重写invocationHandler中的invoke方法,可以根据method的返回类型来给出要返回的默认值 - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
 // 根据方法的返回值类型,生成特定的默认值对象
 Class<?> methodReturnType = method.getReturnType();
 // log.info("mock invoke {}", method.getName());
 return getDefaultObject(methodReturnType);
 }
 private Object getDefaultObject(Class<?> type){
 // 基本类型
 if(type.isPrimitive()){
 if(type == boolean.class){
 return false;
 }
 else if(type == short.class){
 return (short)0;
 }
 else if(type == int.class){
 return 0;
 }
 else if(type == long.class){
 return 0L;
 }
 }
 // 对象类型
 return null;
 }
- 然后就可以通过Proxy.newProxyInstance()方法依次传入要实现的类的加载器classLoader、类数组、自定义的处理器 - 1 
 2
 3
 4
 5
 6- public static <T> T getMockProxy(Class<T> serviceClass){ 
 return (T)Proxy.newProxyInstance(
 serviceClass.getClassLoader(),
 new Class[]{serviceClass},
 new MockServiceProxy());
 }