Java 知识 - 接口代理


介绍

模仿 Mybatis 的接口代理,自己模仿写一下。

接口

public interface MyInterface {
  public List getString(String a, String b);
}

代理(未做到通用)

public class MyProxy implements InvocationHandler {
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Select annotation = method.getAnnotation(Select.class);
    if(annotation != null) {
      System.out.println("SQL:" + annotation.value()[0]);
    }
    // 模拟数据库查询 SQL 操作
    ArrayList list = new ArrayList();
    list.add(args[0]);
    list.add(args[1]);
    return list;
  }
}

代理工厂

public class ProxyFactory {
  public Object getProxyInstance(Class mapper){
    ClassLoader classLoader = ProxyFactory.class.getClassLoader();
    return Proxy.newProxyInstance(classLoader,  new Class[] { mapper }, new MyProxy());
  }
}

测试

public class Mytest {
  public static void main(String[] args) {
    ProxyFactory proxyFactory = new ProxyFactory();
    MyInterface myInterface = (MyInterface) proxyFactory.getProxyInstance(MyInterface.class);
    List string = myInterface.getString("fei", "gege");
    System.out.println(string.toString());
  }
}

结果:
SQL:select * from users where id = ?
[fei, gege]