private static boolean isNotMyType(String typeName) {
return "java.lang.Integer".equals(typeName)
|| "java.lang.String".equals(typeName)
|| "java.util.Date".equals(typeName)
|| "java.sql.Date".equals(typeName)
|| "java.lang.Double".equals(typeName);
}
private void setValue(Object obj, String property, Object propertyValue) throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException {
Class clazz = obj.getClass();
Field field = clazz.getDeclaredField(property);
if (field != null) {
String typeName = field.getType().getName();
if (isMyType(typeName)) {
Class typeNameClass = Class.forName(typeName);
Constructor constructor = typeNameClass.getDeclaredConstructor(Integer.class);
propertyValue = constructor.newInstance(propertyValue);
}
field.setAccessible(true);
> field.set(obj, propertyValue); 将实例对象赋值给这个属性 显示报错
}
}
java.lang.NoSuchMethodException: java.lang.Double.<init>(java.lang.Integer)
为什么报错啊 因为实体类没有构造方法吗? 都写了啊
typeNameClass.getDeclaredConstructor(Integer.class)
这个是获取参数为一个Integer
的构造方法,没有就会报错,java.lang.Double
就没有只是设置属性的话应该不需要这一步操作,参考代码