当前位置:网站首页>通过方法引用获取方法名
通过方法引用获取方法名
2022-08-02 10:36:00 【夜光下丶】
在学习Mybatis-plus时,可以通过getter方法的方法引用来获取到对应的字段名
LambdaQueryWrapper<PurchaseOrder> wrapper = new LambdaQueryWrapper<>();
wrapper.like(PurchaseOrder::getBillTypeName, order.getBillTypeName());
这种情况避免了魔法值的出现,也不需要手动写死,避免因需求改变而导致的错误
QueryWrapper<OrderDataDTO> wrapper = new QueryWrapper<>();
wrapper.like("bill_type_name", dto.getBillTypeName())
lambda表达式不仅可以通过方法引用简化代码,也可以通过getter/setter的方法引用获取到对应的属性名,避免出现bug
代码实现
函数式接口
首先需要定义一个函数式接口来接受我们的方法引用,该接口必须要继承 Serializable 才能获取到方法信息
@FunctionalInterface
public interface SFunction<T> extends Serializable {
/**
* 获取对象属性信息
*
* @param source
* @return
*/
Object get(T source);
}
函数式接口:如果一个接口中只有一个抽象方法(可以包含多个默认方法或多个static方法),那么该接口就是函数式接口。本质上是将函数的实现直接转换为了一个声明语句的定义,极大简化了原有的实现方式
@FunctionalInterface:用来指定某个接口必须是函数式接口,所以该注解只能修饰接口,加上标注, 则会触发JavaCompiler的检查。对于符合函数接口的接口,加不加都无关紧要,但是加上则会提供一层编译检查的保障。如果不符合,则会报错。
工具类
解析Function获取字段属性名
public class ConvertUtil {
public static final String GET = "get";
public static final String IS = "is";
private static final Map<Class<?>, SerializedLambda> CLASS_LAMBDA_CACHE = new ConcurrentHashMap<>();
/**
* 转换方法引用为属性名
*
* @param fn
* @param <T>
* @return
*/
public static <T> String convertToFieldName(SFunction<T> fn) {
SerializedLambda lambda = getSerializedLambda(fn);
String methodName = lambda.getImplMethodName();
if (methodName.startsWith(GET)) {
methodName = methodName.substring(3);
} else if (methodName.startsWith(IS)) {
methodName = methodName.substring(2);
} else {
throw new IllegalArgumentException("无效的getter方法:" + methodName);
}
return StringUtil.firstToLowerCase(methodName);
}
public static SerializedLambda getSerializedLambda(Serializable fn) {
SerializedLambda lambda = CLASS_LAMBDA_CACHE.get(fn.getClass());
// 先检查缓存中是否存在
if (lambda == null) {
try {
// 提取SerializedLambda并缓存
Method method = fn.getClass().getDeclaredMethod("writeReplace");
method.setAccessible(Boolean.TRUE);
lambda = (SerializedLambda) method.invoke(fn);
CLASS_LAMBDA_CACHE.put(fn.getClass(), lambda);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return lambda;
}
}
/**
* 首字母转换小写
*
* @param str 需要转换的字符串
* @return 转换好的字符串
*/
public static String firstToLowerCase(final String str) {
if (isBlank(str)) {
return EMPTY;
}
return str.substring(0, 1).toLowerCase() + str.substring(1);
}
测试
public static void main(String[] args) {
String firstNameFieldNameStyle = ConvertUtil.convertToFieldName(User::getFirstName);
String firstNameUnderlineStyle = ConvertUtil.convertToUnderline(User::getFirstName);
System.out.println("firstNameFieldNameStyle:" + firstNameFieldNameStyle);
System.out.println("firstNameUnderlineStyle:" + firstNameUnderlineStyle);
}
想要深入研究的可以看这个链接:Lambda表达式获取传入的方法引用的方法名_社恐Coder的博客-CSDN博客
边栏推荐
- windbg分析进程卡死
- LayaBox---TypeScript---三斜线指令
- 循环结构--while循环
- 21年毕业转行软件测试,从0收入到月薪过万,我真的很幸运...
- LayaBox---TypeScript---JSX
- 循环语句综合练习
- R language ggplot2 visualization: use the ggbarplot function of the ggpubr package to visualize the horizontal column chart (bar chart), use the orientation parameter to set the column chart to be tra
- Geoffery Hinton: The Next Big Thing in Deep Learning
- You Only Hypothesize Once: 用旋转等变描述子估计变换做点云配准(已开源)
- 如何在技术上来保证LED显示屏质量?
猜你喜欢
MySql tens of millions of paging optimization, fast insertion method of tens of millions of data
FPGA手撕代码——CRC校验码的多种Verilog实现方式 (2021乐鑫科技数字IC提前批代码编程)
The realization of the list
只问耕耘,不问收获,其实收获却在耕耘中
博云入选Gartner中国DevOps代表厂商
ASP.NET Core 6框架揭秘实例演示[31]:路由&quot;高阶&quot;用法
How to choose a truly "easy-to-use, high-performance" remote control software
字节跳动软件测试岗,收到offer后我却拒绝了~给面试的人一些忠告....
Hello, my new name is "Bronze Lock/Tongsuo"
Three.JS程序化建模入门
随机推荐
超赞!发现一个APP逆向神器!
5G基础学习1、5G网络架构、网络接口及协议栈
深度学习100例 —— 卷积神经网络(CNN)实现mnist手写数字识别
LayaBox---TypeScript---Mixins
只问耕耘,不问收获,其实收获却在耕耘中
从零开始Blazor Server(5)--权限验证
365天挑战LeetCode1000题——Day 047 设计循环队列 循环队列
3D激光slam:LeGO-LOAM---地面点提取方法及代码分析
bgp与mpls综合实验
R language time series data arithmetic operation: use the log function to log the time series data, and use the diff function to calculate the successive difference of the logarithmic time series data
The 38-year-old daughter is not in love and has no stable job, the old mother is crying
软件测试岗位巨坑?阿里在职7年测试人告诉你千万别上当
利用二维数据学习纹理三维网格生成(CVPR 2020)
The R language uses the rollapply function in the zoo package to apply the specified function to the time series in a rolling manner and the window moves, and set the align parameter to specify that t
LayaBox---TypeScript---高级类型
[Science of Terminology] For those difficult words about the integrated workbench, read this article to understand in seconds!
3 d laser slam: LeGO - LOAM - ground point extracting method and the analysis of the code
全新荣威RX5,27寸大屏吸引人,安全、舒适一个不落
MySql千万级分页优化,快速插入千万数据方法
LayaBox---TypeScript---迭代器和生成器