ioc测试
程序员文章站
2022-05-23 10:40:41
...
person实体
通过一个string的参数,获取相应的对象
测试结果
输出结果:[name=test1,age=12,sex=男]
public class Person {
private String name;
private String age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "[name="+name+",age="+age+",sex="+sex+"]";
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
通过一个string的参数,获取相应的对象
public class ObjectService {
private Object obj;
private List<Map<String, String>> list;
public ObjectService() {
/*
* 这里假设list是个数据集,可以用resultset代替
*/
list = new ArrayList<Map<String, String>>();
Map<String, String> map = new HashMap<String, String>();
map.put("name", "test1");
map.put("sex", "男");
map.put("age", "12");
list.add(map);
}
public Object getObject(String className) {
Class<?> a = null;
try {
// 通过字符串加载类
a = Class.forName("com.victop.beans." + className);
// 实例化
obj = a.newInstance();
// 获得a类中声明的字段
Field[] fields = a.getDeclaredFields();
// 遍历字段
for (Field field : fields) {
for (int i = 0; i < list.size(); i++) {
Map<String, String> map = (Map<String, String>) list.get(i);
Set<String> set = map.keySet();
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String keyString = (String) iterator.next();
//如果key值同类的属性名相同,那么将这个value set给该属性
if (keyString.equals(field.getName())) {
field.setAccessible(true);//可以访问private属性
field.set(obj, map.get(keyString));
break;
}
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
}
测试结果
public class Test {
public static void main(String[] agrs) {
ObjectService objectService = new ObjectService();
Person person = (Person) objectService.getObject("Person");
System.out.println(person);
}
}
输出结果:[name=test1,age=12,sex=男]
上一篇: 类与对象