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");
}
}
网友评论