今天要聊的是基于函数式编程如何拿到对应方法的getter方法对应你的属性名称
比如
String nickname = Util.getPropertyName(people::getNickname);// 拿到的就是“nickname”
正题,欲拿到对应实体类getter方法对应的属性名称。需自定义一个函数式注解,该注解继承自
Function注解。且必须继承自Serializable注解(作用,必须实例化才能玩“writeReplace”)
上代码
1.定义函数式接口
@FunctionalInterface
interface PropertyFunc extends Function, Serializable {
}
2.定义获取getter方法对应的属性名称的工具方法
public final class PropertyUtil {
// 拿到getter方法对应的属性名称
public static String getFieldName(PropertyFunc field) {
Class> clazz = field.getClass();
try {
Method method = clazz.getDeclaredMethod("writeReplace");
method.setAccessible(true);
SerializedLambda lambda = (SerializedLambda) method.invoke(field);
return uncapitalize(lambda.getImplMethodName());
} catch (Exception e) {
if (!Object.class.isAssignableFrom(clazz.getSuperclass())) {
return getFieldName(field);
}
throw new RuntimeException("current property is not exists");
}
}
// 去掉方法的“get/is”前缀,首字母小写
private static String uncapitalize(String str) {
if (str == null || str.length() < 4) {
return str;
}
String fieldName = str.startsWith("get") ?
str.substring(3) : str.startsWith("is") ? str.substring(2) : str;
return fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
}
}
3.小实验
// 定义一个实体
class People {
private String username;
public String getUsername() {
return username;
}
}
// 测试
public static void main(String[] args) {
System.out.println(PropertyUtil.getFieldName(People::getUsername));
// 打印结果 username
}
完事!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)