天天看點

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;  

    }