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

java反射强制赋值 博客分类: java  

程序员文章站 2024-03-22 10:11:04
...
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;
}

}