熊熊出没 发表于 2022-8-12 10:07:39

Java 知识 - 接口代理

介绍

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

public interface MyInterface {
public List<String> 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());
    }
    // 模拟数据库查询 SQL 操作
    ArrayList list = new ArrayList();
    list.add(args);
    list.add(args);
    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> string = myInterface.getString("fei", "gege");
    System.out.println(string.toString());
}
}结果:
SQL:select * from users where id = ?


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Java 知识 - 接口代理