package com.lightinit.hsdatashow.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author WangYao
 * @date 2018/6/2 11:02
 * @description 注解帮助类
 */
public class AnnotationHelper {

    /**
     * @param clazz 目标类.class
     * @param fieldName 成员变量（字段）名
     * @param clazzAnnotation 注解.class
     * @param <T> 泛型，继承自Annotaion
     * @return 注解类实例或null。
     */
    public static <T extends Annotation> T getFieldAnnotation(Class clazz, String fieldName, Class<T> clazzAnnotation){
        List<Field> fieldList = new ArrayList<>();
        Class tempClass = clazz;
        while (tempClass != null) { //当父类为null的时候说明到达了最上层的父类(Object类).
            Field[] fields = tempClass.getDeclaredFields();
            fieldList.addAll(Arrays.asList(fields));
            tempClass = tempClass.getSuperclass(); //得到父类,然后赋给自己
        }
        if (fieldList == null || fieldList.size() == 0){
            return null;
        }
        Field targetField = null;
        for (Field field : fieldList){
            if (field.getName().equals(fieldName)){
                targetField = field;
                break;
            }
        }
        if (targetField == null){
            return null;
        }
        if (!targetField.isAnnotationPresent(clazzAnnotation)){
            return null;
        }
        return targetField.getAnnotation(clazzAnnotation);
    }


    /**
     * @param object 目标类对象
     * @param fieldName 成员变量（字段）名
     * @param clazzAnnotation 注解.class
     * @param <TObject> 泛型目标类对象
     * @param <TAnnotation> 泛型注解，继承自Annotaion
     * @return 注解类实例或null。
     */
    public static <TObject, TAnnotation extends Annotation> TAnnotation getFieldAnnotation(TObject object, String fieldName, Class<TAnnotation> clazzAnnotation){
        return object == null ? null : getFieldAnnotation(object.getClass(), fieldName, clazzAnnotation);
    }
}
