java 中的:: 双冒号 function参数

分析一下mybatis plus中的构造器 ::
举例: 实体类Entity中 存在name字段
在构造器中 我们写法是 wrapper.lambda.select(Entity::getName)…

其中最核心的部分就是将Function序列化成流 再将流自定义反序列化成 SerializedLambda 对象,在SerializedLambda中定义一个implMethodName字段 存储字符串 “getName” ,并对String做处理 截取Name 替换首字母为小写 name
在这里插入图片描述

demo下载地址

另外有一种更简单的获取方式:

 /**
     * Description: 函数式参数转回String属性名
     * date: 2021/06/09 12:05
     * @param sFunctionField
     * @return
     * @author qkj
     */

    public static <T> String function2Str (SFunction<T, ?> sFunctionField) {
    
    
        Method writeReplace = null;
        try {
    
    
            // 函数式方法可以直接调用writeReplace
            writeReplace = sFunctionField.getClass().getDeclaredMethod("writeReplace");
        } catch (NoSuchMethodException e) {
    
    
            e.printStackTrace();
        }
        writeReplace.setAccessible(true);
        String fieldName = "";
        try {
    
    
            // 序列化
            Object object = writeReplace.invoke(sFunctionField);
            // 反序列化
            SerializedLambda serializedLambda = (SerializedLambda) object;
            String methodName = serializedLambda.getImplMethodName();
            String temp = methodName.substring(3);
            fieldName = temp.replaceFirst(temp.substring(0,1),temp.substring(0,1).toLowerCase());
        } catch (IllegalAccessException e) {
    
    
            e.printStackTrace();
        } catch (InvocationTargetException e) {
    
    
            e.printStackTrace();
        }

        return fieldName;

    }

猜你喜欢

转载自blog.csdn.net/qq_36268103/article/details/116306613