美文网首页
根据get或is方法获取参数名

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

作者: 扮鬼之梦 | 来源:发表于2021-10-13 17:32 被阅读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));
        }
    }
    

    相关文章

      网友评论

          本文标题:根据get或is方法获取参数名

          本文链接:https://www.haomeiwen.com/subject/xjleoltx.html