我需要根据平面文件或Map的输入来调用和示例化n个bean类及其变量。
我在下面尝试使用反射,但这只帮助示例化字符串类型的变量,而不是泛型。请建议。我可以使用任何现有的api或其他东西来处理这个案例研究吗?
public class PersonInstantiator {
public static void main(String[] args) throws Exception{
HashMap<String, String> objHashMap = new HashMap<String, String>();
objHashMap.put("KEY1", "KEY1 VALUE");
objHashMap.put("KEY2", "KEY2 VALUE");
Object object = null;
Class<?> objClass = null;
Properties properties = new Properties();
properties.load(PersonInstantiator.class.getResourceAsStream("MappingFile.txt"));
for (Map.Entry<String, String> entry : objHashMap.entrySet()) {
String input[] = properties.getProperty(entry.getKey()).split("-");
String className = input[0];
String methodName = input[1];
objClass = Class.forName(className);
if (null == object) {
object = objClass.newInstance();
}
Class<?>[] cArg = new Class[1];
cArg[0] = String.class;
Method method = objClass.getDeclaredMethod("set" + methodName, cArg);
method.setAccessible(true);
method.invoke(object, entry.getValue());
}
System.out.println(object);
}
班级成员如下所示:
public class Person {
private String name;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Person [name=" + name + ", city=" + city + "]";
}
}
使用的Map文件包含以下文本。
KEY1 = Person-Name
KEY2 = Person-City
暂无答案!
目前还没有任何答案,快来回答吧!