package com.platform.utils; import com.platform.annotation.NumericValue; import java.lang.reflect.Field; import java.lang.reflect.Method; public class AnnotationUtils { /** * 获取带有指定NumericValue值的字段 * @param target 目标对象 * @param value 要查找的注解值 * @return 匹配的字段,如果没有找到返回null */ public static Field findFieldByNumericValue(Object target, int value) { for (Field field : target.getClass().getDeclaredFields()) { NumericValue annotation = field.getAnnotation(NumericValue.class); if (annotation != null && annotation.value() == value) { return field; } } return null; } /** * 获取字段的getter方法 * @param field 目标字段 * @param clazz 目标类 * @return getter方法,如果没有找到返回null */ public static Method findGetterMethod(Field field, Class clazz) { String fieldName = field.getName(); String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { return clazz.getMethod(getterName); } catch (NoSuchMethodException e) { // 尝试boolean类型的is前缀 if (field.getType() == boolean.class || field.getType() == Boolean.class) { getterName = "is" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { return clazz.getMethod(getterName); } catch (NoSuchMethodException ex) { return null; } } return null; } } }