Java 知识 - 接口代理

打印 上一主题 下一主题

主题 871|帖子 871|积分 2613

介绍

模仿 Mybatis 的接口代理,自己模仿写一下。
接口
  1. public interface MyInterface {
  2.   public List<String> getString(String a, String b);
  3. }
复制代码
代理(未做到通用)
  1. public class MyProxy implements InvocationHandler {
  2.   @Override
  3.   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  4.     Select annotation = method.getAnnotation(Select.class);
  5.     if(annotation != null) {
  6.       System.out.println("SQL:" + annotation.value()[0]);
  7.     }
  8.     // 模拟数据库查询 SQL 操作
  9.     ArrayList list = new ArrayList();
  10.     list.add(args[0]);
  11.     list.add(args[1]);
  12.     return list;
  13.   }
  14. }
复制代码
代理工厂
  1. public class ProxyFactory {
  2.   public Object getProxyInstance(Class mapper){
  3.     ClassLoader classLoader = ProxyFactory.class.getClassLoader();
  4.     return Proxy.newProxyInstance(classLoader,  new Class[] { mapper }, new MyProxy());
  5.   }
  6. }
复制代码
测试
  1. public class Mytest {
  2.   public static void main(String[] args) {
  3.     ProxyFactory proxyFactory = new ProxyFactory();
  4.     MyInterface myInterface = (MyInterface) proxyFactory.getProxyInstance(MyInterface.class);
  5.     List<String> string = myInterface.getString("fei", "gege");
  6.     System.out.println(string.toString());
  7.   }
  8. }
复制代码
结果:
SQL:select * from users where id = ?
[fei, gege]

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

熊熊出没

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表