add method

This commit is contained in:
Looly 2021-08-25 15:25:25 +08:00
parent 9a21da9c78
commit 8e5ad32e70
2 changed files with 35 additions and 2 deletions

View File

@ -2,6 +2,7 @@ package cn.hutool.core.lang.func;
import cn.hutool.core.lang.SimpleCache;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
@ -20,7 +21,7 @@ public class LambdaUtil {
* 解析lambda表达式,加了缓存
* 该缓存可能会在任意不定的时间被清除
*
* @param <T> Lambda类型
* @param <T> Lambda类型
* @param func 需要解析的 lambda 对象无参方法
* @return 返回解析后的结果
*/
@ -31,7 +32,7 @@ public class LambdaUtil {
/**
* 获取lambda表达式函数方法名称
*
* @param <T> Lambda类型
* @param <T> Lambda类型
* @param func 函数无参方法
* @return 函数名称
*/
@ -39,6 +40,32 @@ public class LambdaUtil {
return resolve(func).getImplMethodName();
}
/**
* 获取lambda表达式Getter或Setter函数方法对应的字段名称规则如下
* <ul>
* <li>getXxxx获取为xxxx如getName得到name</li>
* <li>setXxxx获取为xxxx如setName得到name</li>
* <li>isXxxx获取为xxxx如isName得到name</li>
* <li>其它不满足规则的方法名抛出{@link IllegalArgumentException}</li>
* </ul>
*
* @param <T> Lambda类型
* @param func 函数无参方法
* @return 函数名称
* @throws IllegalArgumentException 非Getter或Setter方法
* @since 5.7.10
*/
public static <T> String getFieldName(Func1<T, ?> func) throws IllegalArgumentException {
final String methodName = getMethodName(func);
if (methodName.startsWith("get") || methodName.startsWith("set")) {
return StrUtil.removePreAndLowerFirst(methodName, 3);
} else if (methodName.startsWith("is")) {
return StrUtil.removePreAndLowerFirst(methodName, 2);
} else {
throw new IllegalArgumentException("Invalid Getter or Setter name: " + methodName);
}
}
/**
* 解析lambda表达式,加了缓存
* 该缓存可能会在任意不定的时间被清除

View File

@ -12,6 +12,12 @@ public class LambdaUtilTest {
Assert.assertEquals("getAge", methodName);
}
@Test
public void getFieldNameTest(){
String fieldName = LambdaUtil.getFieldName(MyTeacher::getAge);
Assert.assertEquals("age", fieldName);
}
@Data
static class MyTeacher{
public String age;