edi.rule.util.ZSReflect Maven / Gradle / Ivy
package edi.rule.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.*;
import edi.rule.config.JSRuleMessage;
import edi.rule.work.constant.ZSSign;
import edi.rule.work.custom.JSRuleException;
import edi.rule.work.enums.JavaBaseTypeEnum;
public class ZSReflect {
/**
* 执行反射方法(注意访问权限)
*
反射方法的参数不能设置为接口,应为具体的实现类,否则会报找不到方法的错误,例如:不能用public static test(List list),只能test(ArrayList list)
*
反射方法的参数不能为基础类型,必须是对象类型,例如Integer,如有基础类型则调用同名重载方法
* @param target 为反射方法所在的类
* @param methodName 方法名
* @param params 方法参数数组(不需要声明类型,只需要将参数值数组传入即可,会自动判别参数的类型)
* */
public static Object invoke(Object target,String methodName,Object...params) {
Class>[] classes = null;
if (ZSObject.sizeIsNotEmpty(params)) {
classes = new Class>[params.length];
for (int i=0;i[] classes,Object...params) {
try {
if (target==null) {
throw new JSRuleException(JSRuleMessage.read("target.Object.can't.be.null"));
}
if (target instanceof Class) {
return ((Class>)target).getMethod(methodName,classes).invoke(null,params);
}else {
return target.getClass().getMethod(methodName,classes).invoke(target,params);
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new JSRuleException(e);
}
}
@SuppressWarnings("unchecked")
public static T createObject(Class> clazz,Class>[] parameterTypes,Object...initArgs) {
try {
if (clazz.isPrimitive()) {
throw new JSRuleException(JSRuleMessage.read("cannot.create.objects.of.base.type"));
}
return (T) clazz.getConstructor(parameterTypes).newInstance(initArgs);
} catch (InstantiationException | IllegalAccessException e) {
throw new JSRuleException(e);
} catch (InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public static T createObject(Class> clazz) {
return createObject(clazz,null,new Object[]{});
}
/**
* 是否是抽象类型,如接口或抽象类,null不属于任何类型
* */
public static boolean isAbstractType(Class> type) {
return type != null && (type.isInterface() || Modifier.isAbstract(type.getModifiers()));
}
/**
*
是否是jdk中的类型
* */
public static boolean isJdkType(Class> type){
return type.getClassLoader()==null;
}
/**
*
是否是基础类型的包装类,null不属于任何类型
* */
public static boolean isPrimitiveWrapper(Class> clazz){
try {
return ((Class>) clazz.getField("TYPE").get(null)).isPrimitive();
} catch (Exception e) {
return false;
}
}
/**
*
是否是基础类型,包括String以及基础类型的包装类型的判断
* */
public static boolean isPrimitiveType(Class> clazz){
return clazz==String.class || clazz.isPrimitive() || isPrimitiveWrapper(clazz);
}
/**
*
基础类型转换为包装类型,如果是相同类型相互转换可参考{@link JavaBaseTypeEnum#toWrapperValue(Object)}
* @param type 基础类型的class,如int.class
* @param value 值
* */
public static Object toWrapperValue(Class> type, Object value){
if (type.isPrimitive()){
try {
return JavaBaseTypeEnum.toWrapperType(type).getMethod("valueOf", type).invoke(null, value);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
return value;
}
public static Class>[] getGenericType(Field f,int genericSize){
return getGenericType((ParameterizedType)f.getGenericType(),genericSize,false);
}
public static Class>[] getGenericType(Field f,int genericSize,boolean isRecursion){
return getGenericType((ParameterizedType)f.getGenericType(),genericSize,isRecursion);
}
/**
* @apiNote 获取泛型类型,TypeVariable为泛型字母(如A,R),ParameterizedType为带<>括号的泛型类型
* @param genericType 代表泛型类型
* @param genericSize 代表泛型类型个数,同时也是返回类型的数组个数
* @param isRecursion 是否遍历到最后,获取最右边的最终的泛型,默认为false,获取第一层的泛型类型
* */
private static Class>[] getGenericType(ParameterizedType genericType,int genericSize,boolean isRecursion){
Class>[] classes = new Class>[genericSize];
for (int i=0;i) types[i];
}catch (ClassCastException e) {
if (isRecursion) {
if (types[i] instanceof ParameterizedType) {
return getGenericType((ParameterizedType)types[i],genericSize, true);
}else {
if (types[i] instanceof TypeVariable) {
classes[i] = ((TypeVariable>)types[i]).getGenericDeclaration().getClass();
}else {
throw new JSRuleException(JSRuleMessage.read("unknown.error.when.acquire.generics"));
}
}
}else {
if (types[i] instanceof TypeVariable) {
classes[i] = ((TypeVariable>)types[i]).getGenericDeclaration().getClass();
}else {
classes[i] = (Class>)((ParameterizedType)types[i]).getRawType();
}
}
}
}
return classes;
}
/**
* @apiNote 暂时需要有无参的构造函数,构造函数的参数不能是基础类型
* */
public static Object createArray(Class> clazz,int size,Object...constructorParameters) {
Class>[] classes = null;
if (ZSObject.sizeIsNotEmpty(constructorParameters)) {
classes = new Class>[constructorParameters.length];
for (int i=0;i创建数组,constructorParametersType大小应该和constructorParameters大小相同
* @param clazz 数组的类型,当为基础类型或者抽象类型时将直接反回数组,否则依据参数构建对象数组
* @param size 数组的大小
* @param constructorParametersType 对象的构造函数参数类型,为null时表示没有
* @param constructorParameters 对象的构造函数参数实际值,为null时表示没有
* */
public static Object createArray(Class> clazz,int size,Class>[] constructorParametersType,Object...constructorParameters) {
Object array = Array.newInstance(clazz,size);
if (clazz.isPrimitive() || isAbstractType(clazz)) {
return array;
}
try {
Constructor> c;Object value;
for (int i=0;i getFields(Class> target,Class> superClass,boolean isDeclared){
List result = new ArrayList<>();
Collections.addAll(result,isDeclared?target.getDeclaredFields():target.getFields());
if (superClass != null) {
List> list = getSuperClass(target,superClass);
if (ZSVessel.isNotEmpty(list)){
for (Class> c: list) {
Collections.addAll(result,isDeclared?c.getDeclaredFields():c.getFields());
}
}
}
return result;
}
@SafeVarargs
public static List getFieldsByAnnotations(Class> target,Class> superClass,boolean isDeclared,Class extends Annotation>...annotations) {
List result = new ArrayList<>();
for (Field field:getFields(target,superClass,isDeclared)) {
for (Class extends Annotation> a:annotations) {
if (field.isAnnotationPresent(a)) {
result.add(field);
break;
}
}
}
return result;
}
public static List> getAllClassOfPackage(String packagePath){
List> result = new ArrayList<>();
List fileNames = ZSIo.getAllFileNameOfPackage(packagePath,".class",new ArrayList<>());
for (String name:fileNames) {
try {
result.add(Class.forName(name.replaceAll(ZSSign.SLASH_STR, ZSSign.DOT_STR)));
}catch (ClassNotFoundException e) {
throw new JSRuleException(e);
}
}
return result;
}
/**
* 根据参数所指定的类型获取目标对象中符合该类型的属性,暂不支持内部类,内部类的类型有$符号
* @param targetObject 目标对象
* @param objectList 对象类型list,cutPoint需要输入全路径,例如java.lang.String,com.xx.mqa.manage.xx.xx.xx.FatherTest
* @param baseTypeList 基础类型list,int,double
* @param stop 直到某个父类为止
* @return 所有符合指定类型的类中声明的变量名list
*/
public static List getFieldsByType(Object targetObject,List objectList,List baseTypeList,Class> stop) {
List result = new LinkedList<>();
List> superClassList = getSuperClass(targetObject.getClass(),stop);
if (ZSVessel.isNotEmpty(superClassList)){
for (Class> aClass : superClassList) {
Field[] fields = aClass.getDeclaredFields();
int objectListSize = objectList == null ? 0 : objectList.size();
int baseTypeListSize = baseTypeList == null ? 0 : baseTypeList.size();
for (Field field : fields) {
Class> f = field.getType();
if (baseTypeListSize != 0 && f.isPrimitive()) { //如果是基础类型
for (int i = 0; i < baseTypeListSize; i++) {
if (f.getName().equals(baseTypeList.get(i))) {
result.add(field);
}
}
} else if (objectListSize != 0 && !f.isPrimitive()) { //如果是对象类型
for (int i = 0; i < objectListSize; i++) {
if (f.getName().equals(objectList.get(i))) {
result.add(field);
}
}
}
}
}
}
return new ArrayList<>(result);
}
/**
* 逐级向上查找父类
* @param target 需要查找父类的目标类
*/
public static List> getSuperClass(Class> target){
return getSuperClass(target,Object.class);
}
/**
* 逐级向上查找父类,直到某一个点结束
* @param target 需要查找父类的目标类
* @param stop 直到寻找到某一个父类为止时这个父类的全限定类名
* @return 向上逐级查找父类,直到指定的某一个类为止
*/
public static List> getSuperClass(Class> target, Class> stop){
Class> superClass = target.getSuperclass();
if (superClass == null || superClass == Object.class || target == stop || !stop.isAssignableFrom(target)){
return null;
}
List> result = new ArrayList<>();
getSuperClass(superClass,stop,result);
if (stop != Object.class){
result.add(stop);
}
return result;
}
private static void getSuperClass(Class> superClass, Class> stop,List> result){
if (superClass == stop){
return;
}
result.add(superClass);
getSuperClass(superClass.getSuperclass(),stop,result);
}
}