/**
* 设置对象中指定的属性值
* @param clazz 对象对应的类
* @param propertyName 属性名
* @param value 属性值
*/
public static void setPropertyValue(Class<?> clazz, String propertyName, String value) {
try {
Object object = clazz.getConstructor().newInstance();
MetaObject metaObject = MetaObject.forObject(object, new DefaultObjectFactory(),
new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
if (metaObject.hasSetter(propertyName)) {
Class<?> type = metaObject.getSetterType(propertyName);
if (String.class == type) {
metaObject.setValue(propertyName, value);
} else if (int.class == type || Integer.class == type) {
metaObject.setValue(propertyName, Integer.valueOf(value));
} else if (long.class == type || Long.class == type) {
metaObject.setValue(propertyName, Long.valueOf(value));
} else if (short.class == type || Short.class == type) {
metaObject.setValue(propertyName, Short.valueOf(value));
} else if (byte.class == type || Byte.class == type) {
metaObject.setValue(propertyName, Byte.valueOf(value));
} else if (float.class == type || Float.class == type) {
metaObject.setValue(propertyName, Float.valueOf(value));
} else if (boolean.class == type || Boolean.class == type) {
metaObject.setValue(propertyName, Integer.valueOf(value));
} else if (double.class == type || Double.class == type) {
metaObject.setValue(propertyName, Double.valueOf(value));
} else {
throw new Exception("Unsupported property type for : '" + value + "' of type " + type);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
八、目标类型转换
最新推荐文章于 2021-06-25 15:57:13 发布