天天看點

java 反射應用

1,擷取指定類的所有成員變量,包括父類的成員變量:

java 反射應用

/*** 

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

     *  

     * @param clazz 

     * @return 

     */  

    public static list<field> getallfields(class clazz) {  

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

        if (clazz == null) {  

            return null;  

        }  

        class superclass = clazz.getsuperclass();// father class  

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

                                                                 * java.lang.object 

                                                                 */{  

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

        } else {  

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

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

        field[] fields = clazz.getdeclaredfields();  

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

            field field = fields[i];  

            fieldslist.add(field);  

        return fieldslist;  

    }  

 2,設定指定屬性(私有成員變量)的值

java 反射應用

     * @param obj 

     * @param propertyname 

     *            : property name 

     * @param propertyvalue 

     *            : value of property 

     * @throws securityexception 

     * @throws nosuchfieldexception 

     * @throws illegalargumentexception 

     * @throws illegalaccessexception 

    public static void setobjectvalue(object obj, string propertyname,  

            string propertyvalue) throws securityexception,  

            nosuchfieldexception, illegalargumentexception,  

            illegalaccessexception {  

        if (stringutils.isempty(propertyname)  

                || stringutils.isempty(propertyvalue)) {  

            return;  

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

        field name = clazz.getdeclaredfield(propertyname);  

        name.setaccessible(true);  

        name.set(obj, propertyvalue);  

3,擷取指定屬性(私有成員變量)的值

java 反射應用

     * @param propertyname  :name of property  

    public static object getobjectvalue(object obj, string propertyname)  

            throws securityexception, nosuchfieldexception,  

            illegalargumentexception, illegalaccessexception {  

        if (stringutils.isempty(propertyname)) {  

        return name.get(obj);  

 說明:依賴的jar:commons-lang-2.6.jar