反射的使用

因为要根据不同的数据源查询数据,mapper中的方法除了数据源不一样,其他基本一致,而且未来要拓展新的数据源,因此想到使用反射。代码如下:
public Map commonGetCountyCount(Mapper mapper,String sql,String methodName, String county){
Map map = new HashMap();
try{
Method method = mapper.getClass().getMethod(methodName,String.class);
map = (Map) method.invoke(commonQuery,sql);
}catch (Exception e){
map.put("MSG",county+"查询异常:"+e.getMessage());
e.printStackTrace();
}
return map;
}

以后要添加新的数据源时,直接在mapper中写方法,实现类中可以减少很多代码,改动也方便。以下为mapper中代码:
@DS("test")
@Select("${sql}")
Map jzqCommonQuery(@Param("sql") String sql);
原文地址:https://www.cnblogs.com/shihx/p/12034680.html