介绍
模仿 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()[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> string = myInterface.getString("fei", "gege");
- System.out.println(string.toString());
- }
- }
复制代码 结果:
SQL:select * from users where id = ?
[fei, gege]
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |