cool.linco.common.convert.FieldNameUtil Maven / Gradle / Ivy
The newest version!
package cool.linco.common.convert;
import java.beans.Introspector;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* @author linco
* 从传入方法获取字段名
*/
public class FieldNameUtil {
@FunctionalInterface
public interface SFunction extends Function, Serializable {
}
private static Map, String> cache = new ConcurrentHashMap<>();
public static String getField(SFunction, ?> function) {
return cache.computeIfAbsent(function, FieldNameUtil::findField);
}
private static String findField(SFunction, ?> function) {
try {
// 第1步 获取SerializedLambda
Method method = function.getClass().getDeclaredMethod("writeReplace");
method.setAccessible(Boolean.TRUE);
SerializedLambda serializedLambda = (SerializedLambda) method.invoke(function);
// 第2步 implMethodName 即为Field对应的Getter方法名
String implMethodName = serializedLambda.getImplMethodName();
if (implMethodName.startsWith("get") && implMethodName.length() > 3) {
implMethodName = implMethodName.substring(3);
} else if (implMethodName.startsWith("is") && implMethodName.length() > 2) {
implMethodName = implMethodName.substring(2);
}
// 命名风格转换
return Introspector.decapitalize(implMethodName);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy