java反射强制赋值

package com.my.reflect;

import java.lang.reflect.Field;

/**
* 反射赋值
* @author mengyao
*
*/
public class ReflectSet {

/**
* 用于对类的字段赋值,无视private,project修饰符,无视set/get方法
* @param c 要反射的类
* @param args 类的字段名和值 每个字段名和值用英文逗号隔开
* @return
*/
public static Object getInstance(Class<?> caz, String... args) {
try {
//装载指定类后创建类对象
Object object = Class.forName(caz.getName()).newInstance();
//通过实例对象取得用取得在内存中该实际类型class对象的引用
Class<?> obj = object.getClass();
Field[] fields = obj.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);
for (int j = 0; j < args.length; j++) {
String str = args[j];
String strs[] = str.split(",");
if (strs[0].equals(fields[i].getName())) {
fields[i].set(object, strs[1]);
break;
}
}
}
return object;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}


public static void main(String[] args) {
Object object=getInstance(SendInfo.class,"destID,01201101","mobile,15810022404","content,测试数据。");
SendInfo sms=(SendInfo)object;
System.out.println("短信内容:"+sms.getContent());
System.out.println("手机号码:"+sms.getMobile());
System.out.println("尾号:"+sms.getDestID());
//String.class==new String().getClass()结果为true,
//String.class是通过类名的引用取得在内存中该类型class对象的引用;new String().getClass()是通过实例对象取得用取得在内存中该实际类型class对象的引用
System.out.println(String.class==new String().getClass());
}

}
class SendInfo {

private String destID;
private String mobile;
private String content;

public SendInfo() {

}

public SendInfo(String destID, String mobile, String content) {
this.destID = destID;
this.mobile = mobile;
this.content = content;
}

public String getDestID() {
return destID;
}
public void setDestID(String destID) {
this.destID = destID;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值