public <T> SFunction<T, ?> getterFunction(Class<T> clazz, String field) {
Method[] methods = clazz.getMethods();
Method targetMethod = null;
for (Method method : methods) {
if (field.startsWith("is") && StringUtils.equals(method.getName(), field)) {
targetMethod = method;
break;
} else if (StringUtils.equalsIgnoreCase(method.getName(), "get" + field)) {
targetMethod = method;
break;
}
}
Class<?> returnType = targetMethod.getReturnType();
// 创建一个Function,该方法通过反射调用上述方法
Method finalTargetMethod = targetMethod;
SFunction<T, ?> function = input -> {
try {
return finalTargetMethod.invoke(input); // 注意:这里需要确保input是合适的类型,例如String类型对于length()方法。
} catch (Exception e) {
throw new RuntimeException(e);
}
};
return function;
}
网友评论