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

vip.breakpoint.utils.ReflectUtils Maven / Gradle / Ivy

The newest version!
package vip.breakpoint.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author : breakpoint
 * create on 2022/08/27
 * 欢迎关注公众号 《代码废柴》
 */
public class ReflectUtils {

    // 获取一个类里面左右的方法
    public static  List getMethodsFromClazz(Class clazz) {
        List res = new ArrayList();
        Class superclass = clazz.getSuperclass();
//        if (null != superclass && !superclass.isInterface()) {
//            // 将所有的 ExcelField 加入
//            res.addAll(getMethodsFromClazz(superclass));
//        }
        if (!clazz.isInterface()) {
            //Field[] declaredFields = clazz.getDeclaredFields();
            Method[] methods = clazz.getMethods();
            res.addAll(new ArrayList<>(Arrays.asList(methods)));
        }
        return res;
    }


    /**
     * get all field
     *
     * @param clazz clazz for every class
     * @param    type
     * @return all fields from this class
     */
    public static  List getFieldsFromClazz(Class clazz) {
        List res = new ArrayList();
        Class superclass = clazz.getSuperclass();
        if (null != superclass && !superclass.isInterface()) {
            // 将所有的 ExcelField 加入
            res.addAll(getFieldsFromClazz(superclass));
        }
        if (!clazz.isInterface()) {
            Field[] declaredFields = clazz.getDeclaredFields();
            res.addAll(new ArrayList<>(Arrays.asList(declaredFields)));
        }
        return res;
    }

    // get field value from special object
    public static Object getFieldValueFromObj(Field field, Object object) throws
            IllegalArgumentException, IllegalAccessException {
        Object res;
        if (field.isAccessible()) {
            res = field.get(object);
        } else {
            field.setAccessible(true);
            res = field.get(object);
            field.setAccessible(false);
        }
        return res;
    }

    // set field value
    public static void setFieldValue2Object(Field field, Object object, Object value) throws
            IllegalArgumentException, IllegalAccessException {
        if (value == null) return;
        if (field.isAccessible()) {
            field.set(object, value);
        } else {
            field.setAccessible(true);
            field.set(object, value);
            field.setAccessible(false);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy