我有一个域对象,为了本问题的目的,我将其称为Person,具有以下私有变量:
String name
int age
每个都有getter和setter。现在我还有一个
Map<String, String>
,其中包含以下条目:name, phil
age, 35
我想列出类Person中所有setter方法的列表,然后通过循环遍历该列表并使用Map中的值调用每个方法。
我无法在网上找到与此非常接近的示例。如果能提供示例将不胜感激。
我有一个域对象,为了本问题的目的,我将其称为Person,具有以下私有变量:
String name
int age
Map<String, String>
,其中包含以下条目:name, phil
age, 35
当然可以!只需通过以下方式获取以 "set" 开头的所有方法:
Class curClass = myclass.class;
Method[] allMethods = curClass.getMethods();
List<Method> setters = new ArrayList<Method>();
for(Method method : allMethods) {
if(method.getName().startsWith("set")) {
setters.add(method);
}
}
现在你已经有了这些方法。你知道如何为类的实例调用它们吗?
你尝试过使用Apache Commons BeanUtils中的BeanUtils.populate()
吗?
BeanUtils.populate(yourObject, propertiesMap);
java.beans
和 java.lang.reflect
。public Object mapToObject(Map<String, Object> input, Class<?> outputType) {
Object outputObject = null;
List<PropertyDescriptor> outputPropertyDescriptors = null;
// Test if class is instantiable with default constructor
if(isInstantiable(outputType)
&& hasDefaultConstructor(outputType)
&& (outputPropertyDescriptors = getPropertyDescriptors(outputType)) != null) {
try {
outputObject = outputType.getConstructor().newInstance();
for(PropertyDescriptor pd : outputPropertyDescriptors) {
Object value = input.get(pd.getName());
if(value != null) {
pd.getWriteMethod().invoke(outputObject, value);
}
}
} catch (InstantiationException|IllegalAccessException|InvocationTargetException|NoSuchMethodException e) {
throw new IllegalStateException("Failed to instantiate verified class " + outputType, e);
}
} else {
throw new IllegalArgumentException("Specified outputType class " + outputType + "cannot be instantiated with default constructor!");
}
return outputObject;
}
private List<PropertyDescriptor> getPropertyDescriptors(Class<?> outputType) {
List<PropertyDescriptor> propertyDescriptors = null;
try {
propertyDescriptors = Arrays.asList(Introspector.getBeanInfo(outputType, Object.class).getPropertyDescriptors());
} catch (IntrospectionException e) {
}
return propertyDescriptors;
}
private boolean isInstantiable(Class<?> clazz) {
return ! clazz.isInterface() && ! Modifier.isAbstract(clazz.getModifiers());
}
private boolean hasDefaultConstructor(Class<?> clazz) {
try {
clazz.getConstructor();
return true;
} catch (NoSuchMethodException e) {
return false;
}
}
我认为你可以使用一个库,Apache Commons BeanUtils。如果你有一个包含字段和值对的映射,类PropertyUtils可以帮助你:
Person person = new Person();
for(Map.Entry<String, Object> entry : map.entrySet())
PropertyUtils.setProperty(person, entry.getKey(), entry.getValue());