All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.alibaba.spring.util.FieldUtils Maven / Gradle / Ivy

package com.alibaba.spring.util;

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * {@link Field} Utilities
 *
 * @author Mercy
 * @see Field
 * @see ReflectionUtils
 * @since 2017.01.22
 */
public abstract class FieldUtils {


    /**
     * Get {@link Field} Value
     *
     * @param object    {@link Object}
     * @param fieldName field name
     * @param        field type
     * @return {@link Field} Value
     */
    public static  T getFieldValue(Object object, String fieldName) {
        return (T) getFieldValue(object, fieldName, null);
    }

    /**
     * Get {@link Field} Value
     *
     * @param object       {@link Object}
     * @param fieldName    field name
     * @param           field type
     * @param defaultValue default value
     * @return {@link Field} Value
     */
    public static  T getFieldValue(Object object, String fieldName, T defaultValue) {

        T value = getFieldValue(object, fieldName);

        return value != null ? value : defaultValue;
    }

    /**
     * Get {@link Field} Value
     *
     * @param object    {@link Object}
     * @param fieldName field name
     * @param fieldType field type
     * @param        field type
     * @return {@link Field} Value
     */
    public static  T getFieldValue(Object object, String fieldName, Class fieldType) {

        T fieldValue = null;

        Field field = ReflectionUtils.findField(object.getClass(), fieldName, fieldType);

        if (field != null) {

            boolean accessible = field.isAccessible();

            try {

                if (!accessible) {
                    ReflectionUtils.makeAccessible(field);
                }

                fieldValue = (T) ReflectionUtils.getField(field, object);

            } finally {

                if (!accessible) {
                    field.setAccessible(accessible);
                }

            }

        }

        return fieldValue;

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy