使用反射實現遍歷bean的屬性

在某些情況下,我們需要對bean的屬性進行遍歷處理,使用getXXX方法未免過於繁瑣,特別是對屬性處理的相同時,如:動態拼接SQL。基於此需求,本人採用反射機制對遍歷bean做了一個簡單的實現。

實現思路

關於實現bean屬性的遍歷主要有三種方式 1.調用getXXX方法。 2. 將其轉換爲序列化JSON再轉成Map或者JsonObject對象. 3.使用反射機制獲取getXXX方法,進行遍歷。以下實現使用了第三種方式(可以使用Hutool中的BeanUtil.beanToMap實現)

具體實現

   /**
    * <p>Title: BeanPropCache.java</p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2020</p>
    * 
    * @author sliver
    * @date 2020年3月29日
    * @version 1.0
    */
   package com.iipcloud.base;
   
   import java.lang.reflect.Method;
   import java.util.ArrayList;
   import java.util.List;
   import java.util.concurrent.ExecutionException;
   
   import com.google.common.cache.Cache;
   import com.google.common.cache.CacheBuilder;
   
   /**
    * Title: BeanPropCache
    * Description:
    * 
    * @author sliver
    * @date 2020年3月29日
    */
   enum BeanPropCache {
       ME;
       private final Cache<Class<? extends IForeachAbleBean>, List<BeanProp>> cache;
   
       BeanPropCache() {
           cache = CacheBuilder.newBuilder().build();
       }
   
       public List<BeanProp> getBeanProp(Class<? extends IForeachAbleBean> beanClass) {
           try {
               return cache.get(beanClass, () -> {
                   Method[] methods = beanClass.getDeclaredMethods();
                   List<BeanProp> beanProps = new ArrayList<>(methods.length);
                   for (Method method : methods) {
                       String methodName = method.getName();
                       boolean isGetMethod = methodName.startsWith("get") && method.getParameterCount() == 0;
                       if (isGetMethod) {
                           BeanProp prop = BeanProp.of(method);
                           beanProps.add(prop);
   
                       }
                   }
                   return beanProps;
               });
           } catch (ExecutionException e) {
               throw new RuntimeException(e);
           }
       }
   
   }

    
 /**
  * <p>Title: BeanProp.java</p>
  * <p>Description: </p>
  * <p>Copyright: Copyright (c) 2020</p>
  * 
  * @author sliver
  * @date 2020年3月29日
  * @version 1.0
  */
 package com.iipcloud.base;
 
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Type;
 
 import com.jfinal.kit.StrKit;
 
 /**
  * Title: BeanProp
  * Description: bean類中的屬性
  * 
  * @author sliver
  * @date 2020年3月29日
  * @since JDK1.8
  */
 public class BeanProp {
     /** name 屬性名稱 */
     private final String name;
     /** value 屬性值 */
     private final Object value;
     /** type 屬性類型 */
     private final Type type;
     private final Method getter;
 
     static BeanProp of(BeanProp prop) {
         return new BeanProp(prop.getName(), null, prop.getType(), prop.getGetter());
     }
 
     static BeanProp of(BeanProp prop, IForeachAbleBean object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
         Object value = prop.getGetter().invoke(object);
         return new BeanProp(prop.getName(), value, prop.getType(), prop.getGetter());
     }
 
     static BeanProp of(Method getter) {
         String methodName = getter.getName();
         boolean isGetMethod = methodName.startsWith("get") && getter.getParameterCount() == 0;
         if (!isGetMethod) {
             throw new IllegalArgumentException("only accept getXXX method");
         }
         String name = StrKit.firstCharToLowerCase(methodName.substring(3));
         return new BeanProp(name, null, getter.getReturnType(), getter);
     }
 
     BeanProp(String name, Object value, Type type, Method getter) {
         super();
         this.name = name;
         this.value = value;
         this.type = type;
         this.getter = getter;
     }
 
     public String getName() {
         return name;
     }
 
     public Object getValue() {
         return value;
     }
 
     public Type getType() {
         return type;
     }
 
     public Method getGetter() {
         return getter;
     }
 
 }

/**
 * <p>Title: IBean.java</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2020</p>
 * 
 * @author sliver
 * @date 2020年3月29日
 * @version 1.0
 */
package com.iipcloud.base;

import java.util.List;
import java.util.function.Consumer;

import com.google.common.base.Objects;

/**
 * Title: IBean
 * Description:
 * 
 * @author sliver
 * @date 2020年3月29日
 * @since JDK1.8
 */
public interface IForeachAbleBean {

    /**
     * Title: forEach
     * Description: 遍歷bean屬性(遍歷修飾符爲public的getXXX方法)
     * 2020年3月29日
     * 
     * @param consumer
     * @param types    指定屬性類型集合
     */
    default void forEach(Consumer<BeanProp> consumer, Class<?>... types) {
        List<BeanProp> beanProps = BeanPropCache.ME.getBeanProp(this.getClass());
        boolean noAssignType = types.length == 0;
        for (BeanProp beanProp : beanProps) {
            try {
                if (noAssignType) {
                    consumer.accept(BeanProp.of(beanProp, this));
                } else {
                    for (Class<?> item : types) {
                        if (Objects.equal(beanProp.getType(), item)) {
                            consumer.accept(BeanProp.of(beanProp, this));
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * Title: forEachAssignProps
     * Description: 遍歷指定的屬性
     * 2020年3月29日
     * 
     * @param consumer
     * @param propNames
     */
    default void forEachAssignProps(Consumer<BeanProp> consumer, String... propNames) {

        List<BeanProp> beanProps = BeanPropCache.ME.getBeanProp(this.getClass());
        boolean noAssignProp = propNames.length == 0;
        for (BeanProp beanProp : beanProps) {
            try {
                if (noAssignProp) {
                    consumer.accept(BeanProp.of(beanProp, this));
                } else {
                    for (String propName : propNames) {
                        if (Objects.equal(beanProp.getName(), propName)) {
                            consumer.accept(BeanProp.of(beanProp, this));
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}

總結

  1. 從性能的角度來看,直接調用getXXX的方式性能是最好的。反射次之,序列化再反序列化最差。
  2. 與之對應的getXXX方法最是繁瑣,反射的實現難度最高,而轉JSON在反轉爲對象是java程序員的的基本技能。
  3. 在上述的實現過程中使用了緩存機制緩存getXXX方法,對性能的提升有一定的效果.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章