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

io.github.kits.ReflectKit Maven / Gradle / Ivy

The newest version!
package io.github.kits;

import io.github.kits.exception.ReflectiveException;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 反射工具类
 *
 * @project: kits
 * @created: with IDEA
 * @author: kits
 * @date: 2018 11 21 2:52 PM | November. Wednesday
 */
public class ReflectKit {

	private static final ConcurrentHashMap> FIELDS = new ConcurrentHashMap<>();

	/**
	 * 获取class的字段
	 * 包括父类的
	 *
	 * @param tClass 资源类
	 * @return 字段集合
	 */
	public static List getFields(Class tClass) {
		List fieldList = FIELDS.get(tClass);
		if (ListKit.isNull(fieldList)) {
			fieldList = new ArrayList<>();
			ListKit.add2List(fieldList, tClass.getDeclaredFields());
			while (Objects.nonNull(tClass.getSuperclass()) && !EnvKit.isBasicType(tClass.getSuperclass())) {
				ListKit.add2List(fieldList, tClass.getSuperclass()
												  .getDeclaredFields());
				tClass = tClass.getSuperclass();
			}
			FIELDS.put(tClass, fieldList);
		}
		return fieldList;
	}

	/**
	 * Execute the setter method
	 *
	 * @param tClass Class Type
	 * @param object Object
	 * @param field  Field
	 * @param param  Paramter
	 * @param     Generic
	 */
	public static  void invokeSetMethod(Class tClass, Object object, Field field, Object param) {
		String name = complexSetMethodName(field.getName());
		try {
			Method method = tClass.getDeclaredMethod(name, field.getType());
			method.invoke(object, param);
		} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
			if (Objects.nonNull(tClass.getSuperclass()) && !EnvKit.isBasicType(tClass.getSuperclass())) {
				invokeSetMethod(tClass.getSuperclass(), object, field, param);
			} else {
				throw new ReflectiveException(e);
			}
		}
	}

	/**
	 * 完善字段setter方法名
	 *
	 * @param fieldName 字段名称
	 * @return 修改后的值
	 */
	public static String complexSetMethodName(String fieldName) {
		return "set" + StringKit.toUpper1(fieldName);
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy