java.lang.NoSuchMethodException

错误信息:

java.lang.NoSuchMethodException: cn.xxxxx.core.entity.DepartmentDO.setName

getMethod,getDeclaredMethod。看了下说明大概的意思就是getMethod只能调用public声明的方法,而getDeclaredMethod基本可以调用任何类型声明的方法

java.lang.NoSuchMethodException_第1张图片

代码实现:

private List convertDepartmentList(List> list) {
List titleList = list.get(0);
List departmentDOList = new ArrayList<>();
for (int i = 1; i < list.size(); i++) {
List proList = list.get(i);
DepartmentDO department = new DepartmentDO();
Class clazz = department.getClass();
for (int i1 = 0; i1 < proList.size(); i1++) {
String str = DepartmentEnum.getPro(titleList.get(i1));
String methodName = "set" + str.substring(0, 1).toUpperCase() + str.substring(1, str.length());


try {
Method method = clazz.getDeclaredMethod(methodName, String.class);
method.invoke(department, proList.get(i1));
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
departmentDOList.add(department);


}
return departmentDOList;
}

解决:

method.invoke

需要invoke方法为反射方法添加参数!

你可能感兴趣的:(Java,java)