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

// 把JSON string 转化成类的对象
public static <T> T bindModel(String content, Class<T> 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); 修改呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值