反射工具类

描述:反射工具类,获取类的构造方法、Get/Set方法、属性、属性值;

import com.maxinhai.world.entity.Music;

import java.lang.reflect.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @program: world
 * @description: 类反射工具类
 * @author: XinHai.Ma
 * @create: 2021-06-30 17:24
 */
@SuppressWarnings("all")
public class ClassUtils {


    /**
     * 利用反射获取类中的所有方法包括父类
     * @param object
     * @return
     */
    public static List<String> getMethods(Object object) {
        List<String> result = new ArrayList<>();
        Class<?> objClass = object.getClass();
        // 获取构造方法
        Constructor<?>[] constructors = objClass.getConstructors();
        for (Constructor<?> constructor : constructors) {
            String name = constructor.getName();
            result.add(name);
        }
        // 获取get/set方法
        Method[] methods = objClass.getDeclaredMethods();
        for (Method method : methods) {
            String methodName = method.getName();
            result.add(methodName);
        }
        // 父类
        Type superclassType = objClass.getGenericSuperclass();
        if("com.maxinhai.world.entity.AutoBaseEntity".equals(superclassType.getTypeName())
                || "com.maxinhai.world.entity.AutoBaseEntity".equals(superclassType.getTypeName())) {
            Class<?> superclass = objClass.getSuperclass();
            // 获取get/set方法
            Method[] superMethods = superclass.getDeclaredMethods();
            for (Method method : superMethods) {
                String methodName = method.getName();
                result.add(methodName);
            }
            // 获取构造方法
            Constructor<?>[] superConstructors = superclass.getConstructors();
            for (Constructor<?> constructor : superConstructors) {
                String name = constructor.getName();
                result.add(name);
            }
        }
        return result;
    }


    /**
     * 利用反射获取对象属性和值,不包含父类
     * @param object
     * @param objClass
     * @param result
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    private static void getValues(Object object, Class objClass, Map<String, String> result) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Field[] fields = objClass.getDeclaredFields();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Field field : fields) {
            String fieldName = field.getName();
            Type type = field.getGenericType();
            if("java.lang.String".equals(type.getTypeName())) {
                Method method = (Method) objClass.getMethod("get" + Character.toUpperCase(fieldName.charAt(0))+fieldName.substring(1));
                String value = (String) method.invoke(object);
                if (value != null) {
                    result.put(fieldName, value);
                }
            }
            if("java.lang.Long".equals(type.getTypeName())) {
                Method method = (Method) objClass.getMethod("get" + Character.toUpperCase(fieldName.charAt(0))+fieldName.substring(1));
                Long value = (Long) method.invoke(object);
                if (value != null) {
                    result.put(fieldName, String.valueOf(value));
                }
            }
            if("java.lang.Integer".equals(type.getTypeName())) {
                Method method = (Method) objClass.getMethod("get" + Character.toUpperCase(fieldName.charAt(0))+fieldName.substring(1));
                Integer value = (Integer) method.invoke(object);
                if (value != null) {
                    result.put(fieldName, String.valueOf(value));
                }
            }
            if("java.lang.Double".equals(type.getTypeName())) {
                Method method = (Method) objClass.getMethod("get" + Character.toUpperCase(fieldName.charAt(0))+fieldName.substring(1));
                Double value = (Double) method.invoke(object);
                if (value != null) {
                    result.put(fieldName, String.valueOf(value));
                }
            }
            if("java.time.LocalDateTime".equals(type.getTypeName())) {
                Method method = (Method) objClass.getMethod("get" + Character.toUpperCase(fieldName.charAt(0))+fieldName.substring(1));
                LocalDateTime value = (LocalDateTime) method.invoke(object);
                if (value != null) {
                    result.put(fieldName, formatter.format(value));
                }
            }
            if("java.util.Date".equals(type.getTypeName())) {
                Method method = (Method) objClass.getMethod("get" + Character.toUpperCase(fieldName.charAt(0))+fieldName.substring(1));
                LocalDateTime value = (LocalDateTime) method.invoke(object);
                if (value != null) {
                    result.put(fieldName, format.format(value));
                }
            }
        }
    }


    /**
     * 利用反射获取对象属性和值,包含父类
     * @param object
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     */
    public static Map<String, String> getValues(Object object) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Map<String, String> result = new HashMap<>();
        Class<?> objClass = object.getClass();
        getValues(object, objClass, result);
        Type superclassType = objClass.getGenericSuperclass();
        if("com.maxinhai.world.entity.AutoBaseEntity".equals(superclassType.getTypeName())
                || "com.maxinhai.world.entity.AutoBaseEntity".equals(superclassType.getTypeName())) {
            Class<?> superclass = objClass.getSuperclass();
            Field[] superFields = superclass.getDeclaredFields();
            for (Field field : superFields) {
                getValues(object, superclass, result);
            }
        }
        return result;
    }


    /**
     * 利用反射获取对象所有属性和数据类型
     * @param object
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     */
    public static Map<String, String> getAttributes(Object object) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Map<String, String> result = new HashMap<>();
        Class<?> objClass = object.getClass();
        Field[] fields = objClass.getDeclaredFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            Type type = field.getGenericType();
            String typeName = type.getTypeName();
            result.put(fieldName, typeName);
        }
        Type superclassType = objClass.getGenericSuperclass();
        if("com.maxinhai.world.entity.AutoBaseEntity".equals(superclassType.getTypeName())
                || "com.maxinhai.world.entity.AutoBaseEntity".equals(superclassType.getTypeName())) {
            Class<?> superclass = objClass.getSuperclass();
            Field[] superFields = superclass.getDeclaredFields();
            for (Field field : superFields) {
                String fieldName = field.getName();
                Type type = field.getGenericType();
                String typeName = type.getTypeName();
                result.put(fieldName, typeName);
            }
        }
        return result;
    }


    public static void main(String[] args) throws Exception {
        Music music = new Music();
        // 获取类属性
        Map<String, String> attributes = getAttributes(music);
        attributes.forEach((k,v) -> {
            System.out.println(k + "=>" + v);
        });

        System.out.println("");

        // 获取类属性值
        Map<String, String> values = getValues(music);
        values.forEach((k,v) -> {
            System.out.println(k + "=>" + v);
        });

        System.out.println("");

        // 获取类方法
        List<String> methods = getMethods(music);
        methods.forEach(method -> {
            System.out.println(method);
        });
    }

}

  

上一篇:【UE4 C++】打印字符串与输出日志


下一篇:虚幻引擎编程基础(一)