根据get或is方法获取参数名

2021-10-13  本文已影响0人  扮鬼之梦

工具类

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;

public class LambdaUtils {

    private static final String GET = "get";
    private static final String IS = "is";

    public static <T, R> String convertToFieldName(IGetter<T, R> fn) {
        SerializedLambda lambda = getSerializedLambda(fn);
        String methodName = lambda.getImplMethodName();
        String prefix = null;
        if (methodName.startsWith(GET)) {
            prefix = GET;
        } else if (methodName.startsWith(IS)) {
            prefix = IS;
        }
        if (prefix == null || prefix.equals(methodName)) {
            throw new RuntimeException("无效的getter方法: " + methodName);
        }
        return new StringBuilder().append(Character.toLowerCase(methodName.charAt(prefix.length()))).append(methodName.substring(prefix.length() + 1)).toString();
    }

    private static <T, R> SerializedLambda getSerializedLambda(Serializable fn) {
        SerializedLambda lambda;
        try {
            Method method = fn.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(Boolean.TRUE);
            lambda = (SerializedLambda) method.invoke(fn);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return lambda;
    }

    @FunctionalInterface
    public interface IGetter<T, R> extends Serializable {
        R get(T t);
    }
}

实体类

import lombok.Data;

@Data
public class UserDto {
    private String userName;
    private int age;
    private boolean status;
}

测试

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import vip.gnloypp.learn.dto.UserDto;
import vip.gnloypp.learn.util.LambdaUtils;

@SpringBootTest
public class LambdaTests {

    @Test
    public void test() {
        System.out.println(LambdaUtils.convertToFieldName(UserDto::getUserName));
        System.out.println(LambdaUtils.convertToFieldName(UserDto::getAge));
        System.out.println(LambdaUtils.convertToFieldName(UserDto::isStatus));
    }
}
上一篇下一篇

猜你喜欢

热点阅读