需求缘由:因为Mybatis-Plus获得对象中某一个字段值时,一般是默认用get+字段名()
,且字段名首字母大写的方法,但是现在我想实现一个功能,就是传入一个字符串参数,这个字符串记录的是想要获取到的字段名,那么如何根据这个字符串来调用对应的get函数呢?
@TableName("servermonitor")
@Data
public class Servermonitor {
@TableId(type = IdType.AUTO)
private Integer id;
private double cpu0temp;
private double cpu1temp;
private double cpu2temp;
private double cpu3temp;
private double bmctemp;
private double psu1temp;
private double psu2temp;
private double psu1vin;
private double psu2vin;
private double totalpower;
private double cpuwatts;
private double memorywatts;
private double fanwatts;
private double sysfan1;
private double sysfan2;
private double sysfan3;
private double sysfan4;
private double sysfan5;
private double sysfan6;
private double sysfan7;
private double sysfan8;
// @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
private String time;
}
- 最简单的方法(多个if,else if),缺点很明显,字段多的时候写起来很繁琐。不推荐
public Result<?> getparamsList(@RequestParam(defaultValue = "") String search) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
QueryWrapper<Servermonitor> queryWrapper = new QueryWrapper<>();
List<Servermonitor> servermonitorList = servermonitorMapper.selectList(queryWrapper);
List<Object> l = new ArrayList<Object>();
for(int i = 0; i < servermonitorList.size(); ++i) {
if(search == "cpu0temp") l.add(servermonitorList.get(i).getCpu0temp());
else if(search == "cpu1temp") l.add(servermonitorList.get(i).getCpu1temp());
else if(...)
...
...
}
return Result.success(l);
}
- 通过构造函数名来调用对应的字段的get方法,这样比较简洁可扩展
public Result<?> getparamsList(@RequestParam(defaultValue = "") String search) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
QueryWrapper<Servermonitor> queryWrapper = new QueryWrapper<>();
List<Servermonitor> servermonitorList = servermonitorMapper.selectList(queryWrapper);
List<Object> l = new ArrayList<Object>();
String searchFunctionName = "get" + (char)(search.charAt(0) - 32) + search.substring(1, search.length()); //字段首字母大写,构造方法名
for(int i = 0; i < servermonitorList.size(); ++i) {
Servermonitor s = servermonitorList.get(i);
Method method = s.getClass().getMethod(searchFunctionName);
l.add(method.invoke(s));
}
return Result.success(l);
}
getClass()
是获取s
这个对象的对象名
Method Class.getMethod(String name, Class<?>… parameterTypes
)的作用是获得对象所声明的公开方法,该方法的第一个参数name是要获得方法的名字,第二个参数parameterTypes是按声明顺序标识该方法形参类型。
method.invoke(s)
是执行s
对象的method
方法。
有更好的方法请评论一下,一起学习交流。