代码
package com.shunneng.platform.web.rest.util;import javax.persistence.Column;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.function.Function;public class ColumnUtil {@FunctionalInterfacepublic interface SFunction<T, R> extends Function<T, R>, Serializable {}static String defaultSplit = "";static Integer defaultToType = 0;public static <T> String getFieldName(SFunction<T, ?> fn) {return getFieldName(fn, defaultSplit);}public static <T> String getEntityFieldName(SFunction<T, ?> fn) {return getEntityFieldName(fn, defaultSplit);}public static <T> String getFieldName(SFunction<T, ?> fn, String split) {return getFieldName(fn, split, defaultToType,true);}public static <T> String getEntityFieldName(SFunction<T, ?> fn, String split) {return getFieldName(fn, split, defaultToType,false);}public static <T> String getFieldName(SFunction<T, ?> fn, String split, Integer toType, Boolean isAnon) {SerializedLambda serializedLambda = getSerializedLambda(fn);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);}if(isAnon){Column tableField = field.getAnnotation(Column.class);if (tableField != null && tableField.name().length() > 0) {return tableField.name();}}switch (toType) {case 1:return fieldName.replaceAll("[A-Z]", split + "$0").toUpperCase();case 2:return fieldName.replaceAll("[A-Z]", split + "$0").toLowerCase();default:return fieldName.replaceAll("[A-Z]", split + "$0");}}private static <T> SerializedLambda getSerializedLambda(SFunction<T, ?> fn) {Method writeReplaceMethod;try {writeReplaceMethod = fn.getClass().getDeclaredMethod("writeReplace");} catch (NoSuchMethodException e) {throw new RuntimeException(e);}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;}
}
使用方式
ColumnUtil.getEntityFieldName(PlatformConfig::getHosId)