iocテスト

2901 ワード

Personエンティティ

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=test 1,age=12,sex=男性]