欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PropertyDescriptor

程序员文章站 2022-03-03 12:32:24
...
public static void main(String[] args) throws Exception {
		MailForm bean = new MailForm();
		Map propName = new HashMap();
		propName.put("fromAddress", "su");
		propName.put("money", "21");
		Test t = new Test();
		t.setProperties(bean, propName);
		System.out.println(bean.getFromAddress() + " " + bean.getMoney());

	}

	public static void setProperties(Object bean, Map properties) {
		try {

			for (Iterator iter = properties.keySet().iterator(); iter.hasNext();) {
				String propName = (String) iter.next();

				PropertyDescriptor descriptor = new PropertyDescriptor(
						propName, bean.getClass());

				Class propertyType = descriptor.getPropertyType();

				Object value = decode(propertyType, (String) properties
						.get(propName));
				descriptor.getWriteMethod()
						.invoke(bean, new Object[] { value });

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static Object decode(Class type, String value) throws Exception {
		if (type.getName().equals("java.lang.String")) {
			return value;
		}
		if (type.getName().equals("boolean")) {
			return Boolean.valueOf(value);
		}
		if (type.getName().equals("int")) {
			return Integer.valueOf(value);
		}
		if (type.getName().equals("long")) {
			return Long.valueOf(value);
		}
		if (type.getName().equals("float")) {
			return Float.valueOf(value);
		}
		if (type.getName().equals("double")) {
			return Double.valueOf(value);
		}
		if (type.getName().equals("java.awt.Color")) {
			StringTokenizer tokens = new StringTokenizer(value, ",");
			int red = Integer.parseInt(tokens.nextToken());
			int green = Integer.parseInt(tokens.nextToken());
			int blue = Integer.parseInt(tokens.nextToken());
			return new Color(red, green, blue);
		}
		if (type.getName().equals("java.lang.Class")) {
			return Class.forName(value);
		}
		return null;
	}
 
相关标签: Bean