利用反射为类的类型为ArrayList<T>的属性赋值

import java.util.ArrayList;

public class User {

	public String username;

	public ArrayList<Info> infos = new ArrayList<Info>();

	public ArrayList<Info> getInfos() {
		return infos;
	}

	public void setInfos(ArrayList<Info> infos) {
		this.infos = infos;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}

 

public class Info {
	public String address;

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}

 

@SuppressWarnings("unchecked")
	public static ArrayList<Info> addArrayList(String clazzname,
			String arrayListName, Object obj) throws ClassNotFoundException,
			InstantiationException, IllegalAccessException, SecurityException, NoSuchFieldException {
		Info info = (Info) obj;

		Class clazz = Class.forName(clazzname);
		User user = (User) clazz.newInstance();
		Field array = user.getClass().getField(arrayListName);
		ArrayList<Info> infos = (ArrayList<Info>) array.get(user);
		infos.add(info);
		return infos;
	}

	public static void main(String[] s) {
		try {
			Info i = new Info();
			i.setAddress("beijing");
			ArrayList<Info> infos = addArrayList("net.totosea.other.User",
					"infos", i);
			if (infos.size() > 0) {
				for (Info info : infos) {
					System.out.println(info.getAddress());
				}
			}
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

 输出的结果为:beijing

posted @ 2012-03-25 23:10  园林鸟  阅读(3436)  评论(0)    收藏  举报