通过反射给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)
为什么报错啊 因为实体类没有构造方法吗? 都写了啊

阅读 1.6k
1 个回答

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();
        }

    }

}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题