0
点赞
收藏
分享

微信扫一扫

Lambda函数式接口获取字段名称


  1. TypeFunction.java 函数式接口

/**
 * 函数式接口 -  反射 Lambda获取属性值
 *
 * @param <T>
 * @param <R>
 * @author Lance
 * @version 1.0
 * @data 2022/03/24 15:11
 */
@FunctionalInterface
public interface TypeFunction<T, R> extends Serializable, Function<T, R> {

    /**
     * 获取列名称
     *
     * @param lambda
     * @return String
     */
    static String getLambdaColumnName(Serializable lambda) {
        try {
            Method method = lambda.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(Boolean.TRUE);
            SerializedLambda serializedLambda = (SerializedLambda) method.invoke(lambda);
            String getter = serializedLambda.getImplMethodName();
            String fieldName = Introspector.decapitalize(getter.replace("get", ""));
            return fieldName;
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }
}

  1. LambdaUtils.java 获取字段名称工具类

/**
 * 获取字段名
 *
 * @author Lance
 * @version 1.0
 * @data 2022/03/24 16:15
 */
public class LambdaUtils {

    public static <T, R> String getfieldName(TypeFunction<T, R> typeFunction) {
        return TypeFunction.getLambdaColumnName(typeFunction);
    }

}

  1. 使用方式

public static void main(String[] args) {
     // es 对应的实体类
     ElasticOrder pddElasticOrder = new ElasticOrder();
     String fieldName = LambdaUtils.getfieldName(ElasticOrder ::getOrderSn);
     System.out.println("getfieldName = " + getfieldName);
 }

打印结果:orderSn


举报

相关推荐

0 条评论