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

这段代码展示了如何使用Java反射API将JSON字符串转换为指定类的实例,并通过反射方法设置对象的属性。首先,`bindModel`函数尝试将JSON字符串解析为JSONObject,并遍历其键值对,调用`ModelReflector.setProperty`来设置对象的字段。`ModelReflector`类中,`setProperty`方法通过反射获取并调用setter方法来设置对象的属性。这种方法允许动态地修改对象的字段,而无需硬编码getter和setter方法的调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 把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); 修改呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值