结合mybatis-plus实现Function获取java实体类的属性名
1、工具类
package com.yh.tunnel.util;import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.google.common.base.CaseFormat;
import com.yh.tunnel.domain.Plan;import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;/*** @Description* @Date 2019/7/18 10:31* @Author zsj*/
public class TableUtil {//驼峰命名 转下划线命名public static String getColumnName(String fieldName) {String column = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fieldName);return column;}// 下划线命名 转 驼峰命名public static String getFieldName(String columuName) {String fieldName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columuName);return fieldName;}/*** 获取实体类的字段名称*/public static <T> String getFieldName(SFunction<T, ?> fn) {SerializedLambda serializedLambda = getSerializedLambda(fn);// 从lambda信息取出method、field、class等String fieldName = serializedLambda.getImplMethodName().substring("get".length());fieldName = fieldName.replaceFirst(fieldName.charAt(0) + "", (fieldName.charAt(0) + "").toLowerCase());Field field;try {field = Class.forName(serializedLambda.getImplClass().replace("/", ".")).getDeclaredField(fieldName);} catch (ClassNotFoundException | NoSuchFieldException e) {throw new RuntimeException(e);}return fieldName.replaceAll("[A-Z]", "$0");}private static <T> SerializedLambda getSerializedLambda(SFunction<T, ?> fn) {// 从function取出序列化方法Method writeReplaceMethod;try {writeReplaceMethod = fn.getClass().getDeclaredMethod("writeReplace");} catch (NoSuchMethodException e) {throw new RuntimeException(e);}// 从序列化方法取出序列化的lambda信息boolean isAccessible = writeReplaceMethod.isAccessible();writeReplaceMethod.setAccessible(true);SerializedLambda serializedLambda;try {serializedLambda = (SerializedLambda) writeReplaceMethod.invoke(fn);} catch (IllegalAccessException | InvocationTargetException e) {throw new RuntimeException(e);}writeReplaceMethod.setAccessible(isAccessible);return serializedLambda;}public static void main(String[] args) {SFunction<Plan, String> getProperty1Function = Plan::getTunnelId;String propertyName = getFieldName(getProperty1Function);System.out.println("属性名: " + propertyName);}}
2、mybatis-plus 中文排序
SFunction<Plan, String> getProperty1Function = Plan::getName;String propertyName = TableUtil.getFieldName(getProperty1Function);String coloumName = TableUtil.getColumnName(propertyName);QueryWrapper<Plan> wrapper = new QueryWrapper<>();wrapper.lambda().ne(Plan::getName, "无预警");wrapper.orderByDesc("CAST(" + coloumName + " AS CHAR CHARACTER SET gbk)");