MetaClass
MetaClass 实现了对类的属性进行包装,可以对属性进行一系列操作。比如,当一个配置文件和配置类是相对应的,在读取配置文件后,为了防止配置项是规定项,可以对读取到的配置项进行判断:是否有 setter 方法:
/**
* 判断 目标类 中是否定义了 key 指定属性对应的 setter 方法
* @param clazz 目标类
* @param properties 属性列表
* @return true 有 false 没有
*/
public static boolean existProperty(Class<?> clazz, Properties properties) {
//构建 metaClass 对象
MetaClass metaConfig = MetaClass.forClass(clazz, new DefaultReflectorFactory());
for (Object key : properties.keySet()) {
if (!metaConfig.hasSetter(String.valueOf(key))) {
return false;
}
}
return true;
}
MetaObject
/**
* 设置对象中指定的属性值
* @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();
}
}