美文网首页
TestMapperProxy

TestMapperProxy

作者: 不知不怪 | 来源:发表于2020-09-05 23:07 被阅读0次
    package com.gzz.sys.user;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    import java.util.List;
    
    interface SerchDao {
        Object search(String msg);
    }
    
    interface SqlSession {
        List<Object> selectList(String statment);
    }
    
    class DefaultSqlSession implements SqlSession {
        @Override
        public List<Object> selectList(String statment) {
            System.out.println("DefaultSqlSession.selectList");
            return null;
        }
    }
    
    class MapperProxyHandler implements InvocationHandler {
        private SqlSession sqlSession;
        private Class<?> targetInterface;
    
        public MapperProxyHandler(SqlSession sqlSession, Class<?> targetInterface) {
            this.sqlSession = sqlSession;
            this.targetInterface = targetInterface;
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("MapperProxyHandler.invoke");
            String daoName = targetInterface.getName();
            String methodName = method.getName();
            String statement = daoName + "." + methodName;
            return sqlSession.selectList(statement);
        }
    }
    
    class MapperProxyFactory { 
        private Class<?> targetInterface; 
    
        public MapperProxyFactory(Class<?> targetInterface) {
            this.targetInterface = targetInterface;
        }
    
        public Object newInstance(MapperProxyHandler handler) {
            return Proxy.newProxyInstance(targetInterface.getClassLoader(), new Class[] { targetInterface }, handler);
        }
    }
    
    public class TestMapperProxy {
        public static void main(String[] args) {
    
            Class<?> targetInterface = SerchDao.class;
            SqlSession sqlSession = new DefaultSqlSession();
            MapperProxyHandler proxyHandler = new MapperProxyHandler(sqlSession, targetInterface);
            MapperProxyFactory proxyFactory = new MapperProxyFactory(SerchDao.class);
            SerchDao serchDao = (SerchDao) proxyFactory.newInstance(proxyHandler);
            System.out.println(serchDao.getClass().getName());
            serchDao.search("hello mybatis proxy");
        }
    }
    
    

    相关文章

      网友评论

          本文标题:TestMapperProxy

          本文链接:https://www.haomeiwen.com/subject/lzrqektx.html