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

com.gitee.easyopen.util.ReflectionUtil Maven / Gradle / Ivy

package com.gitee.easyopen.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.FatalBeanException;

/**
 * 反射相关
 * @author tanghc
 */
public class ReflectionUtil {

    public static final String PREFIX_SET = "set";
    
    // key:obj.getClass().getName() + genericClass.getName()
    private static Map genericTypeFieldCache = new HashMap<>();
    
    /**
     * 设置某个字段的值
     * @param target 实体类,必须有字段的set方法
     * @param field 字段名
     * @param val 值
     */
    public static void invokeFieldValue(Object target,String fieldName, Object val) {
        String setMethodName = getSetMethodName(fieldName);
        Method[] methods = target.getClass().getDeclaredMethods();
        for (Method method : methods) {
            String methodName = method.getName();
            Class[] methodParams = method.getParameterTypes();
            
            if (setMethodName.equals(methodName)) {
                // 能否拷贝
                boolean canCopy =  methodParams.length == 1 // 并且只有一个参数
                        && methodParams[0].isInstance(val) || Number.class.isInstance(val); // val是methodParams[0]或他的子类
                
                if (canCopy) {
                    try {
                        if (!Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
                            method.setAccessible(true);
                        }
                        method.invoke(target, val);
                        break;
                    } catch (Throwable ex) {
                        throw new FatalBeanException(
                                "Could not set property '" + fieldName + "' value to target", ex);
                    }
                }
            }
        }
    }

    /**
     * 返回实体类中具有指定泛型的字段
     * @param obj 实体类
     * @param genericClass 指定泛型
     * @return 没有返回null
     */
    public static Field getListFieldWithGeneric(Object obj, Class genericClass) {
        Class objClass = obj.getClass();
        String key = objClass.getName() + genericClass.getName();
        Field value = genericTypeFieldCache.get(key);
        if (value != null) {
            return value;
        }
        Field[] fields = objClass.getDeclaredFields();
        for (Field field : fields) {
            Type genericType = getListGenericType(field);
            if (genericType == genericClass) {
                genericTypeFieldCache.put(key, field);
                return field;
            }
        }
        return null;
    }

    /**
     * 返回集合字段的泛型类型。
* 如:List{@literal} list;返回User.class * * @param field * 类中的一个属性 * @return 返回类型 */ public static Type getListGenericType(Field field) { if (isListType(field.getType())) { Type genericType = field.getGenericType(); if (genericType instanceof ParameterizedType) { Type[] params = ((ParameterizedType) genericType).getActualTypeArguments(); if (params.length == 1) { return params[0]; } } } return Object.class; } public static boolean isListType(Type type) { return type == List.class; } /** * 返回set方法名。name -> setName * @param fieldName * @return */ public static String getSetMethodName(String fieldName) { return PREFIX_SET + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); } /** * 构建字段名称 * @param methodName 根据get或set方法返回字段名称 * @return 字段名称 */ public static String buildFieldName(String methodName) { return methodName.substring(3, 4).toLowerCase() + methodName.substring(4); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy