Java反射如何获取命名不符合常规标准的getter方法
解决方案
完全可以实现,核心思路是抛弃JavaBean默认的getXxx/isXxx命名规则,自定义命名映射逻辑,再通过反射匹配对应方法即可,以下是可落地的实现方案:
1. 先抽象项目的自定义getter命名规则
以你给出的示例为例,规则可抽象为:普通类型字段xxx对应的getter方法名为 getThe + 字段名首字母大写的结果,如果项目中boolean类型有单独的isTheXxx规则也可以同步补充。
2. 实现通用反射工具方法
你可以参考以下代码实现自定义的getter查找逻辑:
import java.lang.reflect.Method; public class ReflectionUtils { // 自定义getter名称生成规则,可根据项目实际规则修改 private static String generateGetterName(String fieldName) { if (fieldName == null || fieldName.isEmpty()) { throw new IllegalArgumentException("字段名不能为空"); } // 示例规则:getThe + 首字母大写的字段名 return "getThe" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); } /** * 根据字段名查找对应getter方法 * @param clazz 目标类 * @param fieldName 字段名 * @return 匹配的getter方法 * @throws NoSuchMethodException 找不到对应方法时抛出 */ public static Method getCustomGetter(Class<?> clazz, String fieldName) throws NoSuchMethodException { String expectedGetterName = generateGetterName(fieldName); // getter方法无参数,直接按方法名+空参数列表查找 Method getter = clazz.getMethod(expectedGetterName); // 额外校验返回值非void,避免拿到同名的其他方法 if (getter.getReturnType() == void.class) { throw new NoSuchMethodException("方法" + expectedGetterName + "返回值为void,不是合法getter"); } return getter; } // 测试用例 public static void main(String[] args) throws Exception { Employee employee = new Employee(); employee.setName("张三"); employee.setDept("研发部"); // 查找name字段对应的getter Method getNameMethod = getCustomGetter(Employee.class, "name"); String name = (String) getNameMethod.invoke(employee); System.out.println(name); // 输出:张三 // 查找dept字段对应的getter Method getDeptMethod = getCustomGetter(Employee.class, "dept"); String dept = (String) getDeptMethod.invoke(employee); System.out.println(dept); // 输出:研发部 } }
3. 更灵活的适配方案
如果项目中存在多套命名规则,可以把名称生成逻辑抽象成函数参数,适配不同场景:
public static Method getCustomGetter(Class<?> clazz, String fieldName, Function<String, String> nameGenerator) throws NoSuchMethodException { String expectedGetterName = nameGenerator.apply(fieldName); Method getter = clazz.getMethod(expectedGetterName); if (getter.getReturnType() == void.class) { throw new NoSuchMethodException("方法" + expectedGetterName + "不是合法getter"); } return getter; } // 使用示例,针对不同规则传入不同的生成逻辑 // 规则1:getTheXxx Method getter1 = getCustomGetter(Employee.class, "name", field -> "getThe" + field.substring(0,1).toUpperCase() + field.substring(1)); // 规则2:fetchXxx Method getter2 = getCustomGetter(Employee.class, "name", field -> "fetch" + field.substring(0,1).toUpperCase() + field.substring(1));
注意事项
- 查找方法时要校验参数列表,getter通常为无参方法,避免匹配到同名的重载方法
- 如果getter方法不是public修饰,需要调用
method.setAccessible(true)取消访问权限检查 - 若项目中布尔类型字段的getter有单独规则(比如
isTheXxx),可以在名称生成逻辑中增加返回值类型判断,适配对应规则
内容的提问来源于stack exchange,提问作者Suganthan Madhavan Pillai
相关产品推荐
相关产品推荐

