天天看点

Java 反射常用方法

(1)把list 转化为map

场景:系统中有一个字典类,是一个实体类,如下(省略了getter,setter方法):

Java 反射常用方法

/** 

 * data dictionary entity 

 */  

@entity  

@table(name = "t_dictionary")  

public class commondictionary implements cloneable, serializable {  

    private static final long serialversionuid = 0x33d260729eadd26el;  

    /** 

     * 主键id 

     */  

    private long id;  

     * 组id 

    private string groupid;  

     * 键<br />不能取值为key,因为key是关键字 

    private string key2;  

     * 值 

    private string value;  

     * 描述 

    private string description;  

 public commondictionary clone() throws clonenotsupportedexception {  

        return (commondictionary) super.clone();  

    }  

方法如下 :

Java 反射常用方法

/*** 

     *  

     * @param list 

     * @param clazz 

     * @param keyproperty : 该成员变量的值作为map的key 

     * @param valueproperty : 该成员变量的值作为map的value 

     * @return 

    public static map<string,object> parseobjectlist(list list,class clazz,string keyproperty,string valueproperty){  

        map<string,object> map=new hashmap<string, object>();  

        for(int i=0;i<list.size();i++){  

            object obj=list.get(i);  

            field keyf =null;  

            field valuef =null;  

            try {  

                keyf = clazz.getdeclaredfield(keyproperty);  

            } catch (nosuchfieldexception e) {  

                keyf= getspecifiedfield(clazz.getsuperclass()/* 

                                                             * may be null if it is 

                                                             * object . 

                                                             */, keyproperty);  

                // e.printstacktrace();  

            }  

                valuef = clazz.getdeclaredfield(valueproperty);  

                valuef= getspecifiedfield(clazz.getsuperclass()/* 

                                                             */, valueproperty);  

            keyf.setaccessible(true);  

            valuef.setaccessible(true);  

                map.put((string)keyf.get(obj), valuef.get(obj));  

            } catch (illegalargumentexception e) {  

                e.printstacktrace();  

            } catch (illegalaccessexception e) {  

        }  

        return map;  

 依赖的方法:

Java 反射常用方法

     * get specified field 

     * @param fieldname 

    public static field getspecifiedfield(class<?> clazz, string fieldname) {  

        field f = null;  

        if (valuewidget.isnullorempty(clazz)) {  

            return null;  

        try {  

            f = clazz.getdeclaredfield(fieldname);  

        } catch (nosuchfieldexception e) {  

            return getspecifiedfield(clazz.getsuperclass()/* 

                                                         * may be null if it is 

                                                         * object . 

                                                         */, fieldname);  

            // e.printstacktrace();  

        return f;  

 使用实例:

Java 反射常用方法

list<commondictionary> anticounterfeit=dictionaryparam.getlist(constant2.dictionary_group_anticounterfeit_code);  

        qrsettingsbean qrsettingsbean=new qrsettingsbean();  

        map<string,object>map=reflecthwutils.parseobjectlist(anticounterfeit, commondictionary.class, "key2", "value");  

reflecthwutils.setobjectvalue(qrsettingsbean, map);  

        model.addattribute("qrsettingsbean", qrsettingsbean);  

(2)把map 转化为java对象,map的key对应对象的成员变量的名称

Java 反射常用方法

     * 利用反射设置对象的属性值. 注意:属性可以没有setter 方法. 

     * @param obj 

     * @param params 

     * @throws securityexception 

     * @throws nosuchfieldexception 

     * @throws illegalargumentexception 

     * @throws illegalaccessexception 

    public static void setobjectvalue(object obj, map<string, object> params)  

            throws securityexception, nosuchfieldexception,  

            illegalargumentexception, illegalaccessexception {  

        if (valuewidget.isnullorempty(params)) {  

            return;  

        class<?> clazz = obj.getclass();  

        for (iterator it = params.entryset().iterator(); it.hasnext();) {  

            map.entry<string, object> entry = (map.entry<string, object>) it  

                    .next();  

            string key = entry.getkey();  

            object propertyvalue = entry.getvalue();  

            if (valuewidget.isnullorempty(propertyvalue)) {  

                continue;  

            field name = getspecifiedfield(clazz, key);  

            if (name != null) {  

                name.setaccessible(true);  

                name.set(obj, propertyvalue);  

(3)把对象中 值为空字符串的成员变量 ,将其值改为null

Java 反射常用方法

     * 把对象中空字符串改为null 

     * @param obj : 要修改的对象:java bean 

    public static void convertempty2null(object obj)   

            throws securityexception, nosuchfieldexception, illegalargumentexception, illegalaccessexception{  

        list<field> fieldslist =getallfieldlist(obj.getclass());  

        for(int i=0;i<fieldslist.size();i++){  

            field f=fieldslist.get(i);  

            object vobj=getobjectvalue(obj,f );  

            if(f.gettype().getname().equals("java.lang.string") && (vobj instanceof string) ){  

                string str=(string)vobj;  

                if(systemhwutil.empty.equals(str)){  

//                  system.out.println(f.getname());  

//                  system.out.println(f.gettype().getname());  

                    f.setaccessible(true);  

                    f.set(obj, null);  

                }  

Java 反射常用方法

     * get all field ,including fields in father/super class 

    public static list<field> getallfieldlist(class<?> clazz) {  

        list<field> fieldslist = new arraylist<field>();// return object  

        if (clazz == null) {  

        class<?> superclass = clazz.getsuperclass();// father class  

        if (!superclass.getname().equals(object.class.getname()))/* 

                                                                 * java.lang.object 

                                                                 */{  

            // system.out.println("has father");  

            fieldslist.addall(getallfieldlist(superclass));// recursive  

        field[] fields = clazz.getdeclaredfields();  

        for (int i = 0; i < fields.length; i++) {  

            field field = fields[i];  

            // 排除因实现serializable 接口而产生的属性serialversionuid  

            if (!field.getname().equals("serialversionuid")) {  

                fieldslist.add(field);  

        return fieldslist;  

     * 获取指定对象的属性值 

     * @param name 

     *            :field 

    public static object getobjectvalue(object obj, field name)  

        // field f = getspecifiedfield(obj.getclass(), name.getname());  

        if (name == null) {  

            system.out.println("[reflecthwutils.getobjectvalue]"  

                    + obj.getclass().getname() + " does not has field " + name);  

        name.setaccessible(true);  

        return name.get(obj);  

(4)判断两个对象的属性值是否都相等.

Java 反射常用方法

     * 判断两个对象的属性值是否都相等. 

     * @param obj1 

     * @param obj2 

     * @param exclusiveproperties 

     *            : 要过滤的属性 

    public static boolean issamepropertyvalue(object obj1, object obj2,  

            list<string> exclusiveproperties) throws securityexception,  

            illegalargumentexception, nosuchfieldexception,  

            illegalaccessexception {  

        list<field> fieldslist = getallfieldlist(obj1.getclass());  

        for (int i = 0; i < fieldslist.size(); i++) {  

            field f = fieldslist.get(i);  

            if ((!valuewidget.isnullorempty(exclusiveproperties))  

                    && exclusiveproperties.contains(f.getname())) {// 过滤掉,不比较  

            object propertyvalue1 = getobjectvalue(obj1, f);  

            object propertyvalue2 = getobjectvalue(obj2, f);  

            system.out.println(f.getname());  

            if (propertyvalue1 == propertyvalue2) {// if propertyvalue1 is null  

            if (!issamebysimpletypes(propertyvalue1, propertyvalue2)) {  

                return false;  

        return true;  

     * 比较java 基本类型的值是否相同. 

     *            : string,integer,double,boolean 

    public static boolean issamebysimpletypes(object obj1, object obj2) {  

        if (obj1 == obj2) {  

            return true;  

        if (obj1 instanceof integer) {// int  

            integer int1 = (integer) obj1;  

            integer int2 = (integer) obj2;  

            return int1.intvalue() == int2.intvalue();  

        } else if (obj1 instanceof double) {// double  

            double double1 = (double) obj1;  

            double double2 = (double) obj2;  

            return double1.compareto(double2) == 0;  

        } else if (obj1 instanceof boolean) {// double  

            boolean boolean1 = (boolean) obj1;  

            boolean boolean2 = (boolean) obj2;  

            return boolean1.compareto(boolean2) == 0;  

        } else if (obj1 instanceof string) {  

            string str1 = (string) obj1;  

            string str2 = (string) obj2;  

            return str1.equals(str2);  

        } else if (obj1 instanceof timestamp) {  

            timestamp time1 = (timestamp) obj1;  

            timestamp time2 = (timestamp) obj2;  

            return time1.compareto(time2) == 0;  

        } else if (obj1 instanceof java.util.date) {  

            java.util.date time1 = (java.util.date) obj1;  

            java.util.date time2 = (java.util.date) obj2;  

        } else if (obj1 instanceof java.sql.date) {  

            java.sql.date time1 = (java.sql.date) obj1;  

            java.sql.date time2 = (java.sql.date) obj2;  

        return obj1 == obj2;  

    }