package com.gyee.common.util;/*
@author   谢生杰
@date   2022/11/26-15:27
*/

import org.codehaus.jackson.annotate.JsonProperty;

import java.lang.reflect.Field;

public class ReflexUtil {

    public static Object getFieldValueByObject(Object object, String targetFieldName) throws Exception {
        //获取该对象的class
        Class objClass = object.getClass();
        //初始化返回时
        Object result = null;

        //获取所有的属性数组
        Field[] fields = objClass.getDeclaredFields();

        for (Field field : fields) {
            //属性名称
            String currentFieldName = "";

            try {
                boolean has_JsonProperty = field.isAnnotationPresent(JsonProperty.class);
                if (has_JsonProperty) {
                    currentFieldName = field.getAnnotation(JsonProperty.class).value();
                } else {
                    currentFieldName = field.getName();
                }

                if (currentFieldName.equals(targetFieldName)) {
                    field.setAccessible(true);
                    result = field.get(object);

                    return result;
                }
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
