BeanUtils能够将参数封装成一个bean,方法 setProperty,能够对属性进行赋值。可是尤为是要注意的是它会对属性设置默认值,并且默认值会有歧义。 java
好比说Bean TestBean 的某个属性的类型是Integer, this
TestBean testBean = new TestBean(); try { BeanUtils.setProperty(testBean, "testProperty", null) } catch (Exception ex) {..... } System.out.println("testProperty的值为:"+testBean.getTestPropety);
其结果将会输入为0,这无疑是有坑的。 spa
与这个做用相似的Spring MVC有一个BaseCommandController也是能够将请求参数封装成Bean,可是null code
的值不会转换为默认值。使用的时候切记。 orm
若是BeanUtils也想不转换为类型(如 Integer)的默认值(如0),能够使用以下: ip
try { ConvertUtils.register(new IntegerConverter(null), Integer.class); BeanUtils.setProperty(testBean,"testProperty",null) } catch(Exception ex){ ...... }
或者 get
PropertyUtils.getWriteMethod(PropertyUtils.getPropertyDescriptor(this, propertyName)).invoke(this, new Object[]{null});