通过反射给obj对象的property属性赋propertyValue值 出现报错??
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
就没有
只是设置属性的话应该不需要这一步操作,参考代码
public class Library { static void setValue(Object obj, String property, Object propertyValue) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Field field = obj.getClass().getDeclaredField(property);
field.setAccessible(true);
field.set(obj, propertyValue);
}
public static void main(String[] args) throws Exception {
A a = new A();
setValue(a, "d", 1.0);
System.out.println(a);
}
static class A {
private Double d;
@Override
public String toString() {
return d.toString();
}
}
}
以上是 通过反射给obj对象的property属性赋propertyValue值 出现报错?? 的全部内容, 来源链接: utcz.com/p/944641.html