工具类
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));
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。