利用java反射机制动态创建对象

// 把JSON string 转化成类的对象
public static  T bindModel(String content, Class cls) {
		try {
			JSONObject mjson = new JSONObject(content);
			try {
				T instance = cls.newInstance();
				Iterator it = mjson.keys();
				while (it.hasNext()) {
					String next = it.next().toString();
					ModelReflector.setProperty(instance, next, mjson.get(next)
							.toString());
				}
				return instance;
			} catch (IllegalAccessException e) {
			} catch (InstantiationException e) {
			}
		} catch (JSONException e) {
		}
		return null;
	}

// 按JavaBean模式修改对象的field值

public class ModelReflector {

	public static Object setProperty(Object bean, String propertyName,
			Object value) {
		Class clazz = bean.getClass();
		try {
			Field field = clazz.getDeclaredField(propertyName);
			Method method = clazz.getDeclaredMethod(
					getSetterName(field.getName()),
					new Class[] { field.getType() });
			return method.invoke(bean, new Object[] { value });
		} catch (Exception e) {
		}
		return null;
	}

	public static String getGetterName(String propertyName) {
		String method = "get" + propertyName.substring(0, 1).toUpperCase()
				+ propertyName.substring(1);
		return method;
	}

	public static String getSetterName(String propertyName) {
		String method = "set" + propertyName.substring(0, 1).toUpperCase()
				+ propertyName.substring(1);
		return method;
	}
}

上面是通过发射方法修改对象的field,

能不能直接通过field.set(bean, value); 修改呢?

你可能感兴趣的:(Java)