如何利用反射獲得註解的名稱和內部的值

使用httpclient向後端API POST數據的時候, 需要構建POST的param, 如果使用代碼寫的話太不優雅了, 所以考慮一種比較通用的方式實現, 詳見代碼, 我們使用的註解是 fastjson的, 大家可以使用其他的替換, 意思都是相通的


package zhwb.service.util;

import com.alibaba.fastjson.annotation.JSONField;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Date: 13-12-6
 * Time: 上午11:57
 *
 * @author jack.zhang
 */
public abstract class HttpFastJsonUtils {

    private static final Logger LOG = LoggerFactory.getLogger(HttpFastJsonUtils.class);

    public static final List<BasicNameValuePair> convertBeanToBasicParam(Object jsonAnnotationBean) {
        if (jsonAnnotationBean == null) {
            throw new IllegalArgumentException("bean can not be null");
        }
        List<BasicNameValuePair> result = new ArrayList<BasicNameValuePair>();

        Field[] fields = jsonAnnotationBean.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (!field.isAnnotationPresent(JSONField.class)) {  //field上是否有JsonField註解
                throw new IllegalArgumentException("annotation can only be JSONFiled type");
            }
            JSONField jsonField = field.getAnnotation(JSONField.class); //拿到field上的JsonField註解對象
            field.setAccessible(true);
            String fieldString;
            Object fieldValue = null;
            try {
                fieldValue = field.get(jsonAnnotationBean); //反射得到field的值, 注意private需要setAccessible

            } catch (IllegalAccessException e) {
                LOG.error("IllegalAccessException occur {}", e.getMessage());
            }
            if (fieldValue != null) {
                if (field.getType().equals(Date.class)) { //對一些特殊類型做處理
                    fieldString = DateUtil.formatDateToString((Date) fieldValue, "yyyy-MM-dd");
                } else {
                    fieldString = String.valueOf(fieldValue);
                }
                BasicNameValuePair basicNameValuePair = new BasicNameValuePair(jsonField.name(), fieldString);//構建httpclient需要的list
                result.add(basicNameValuePair);
            }
        }
        return result;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章