public class GetFieldName {
public static void main(String[] args) {
String fieldName = noPrefixToHump(AccountBO::getAccountName);
System.out.println(fieldName);
}
@FunctionalInterface
public interface IGetter<T> extends Serializable {
/**
* Apply object.
*
* @param source the source
* @return the object
*/
Object apply(T source);
}
public static <T> String noPrefixToHump(IGetter<T> fn) {
return convert(getGeneralField(fn));
}
public static String convert(String string) {
StringBuilder result = new StringBuilder();
for (char c : string.toCharArray()) {
if (Character.isUpperCase(c)) {
result.append("_").append(Character.toLowerCase(c));
} else {
result.append(c);
}
}
return result.toString();
}
/**
* 获得set或get或is方法对应的标准属性名,其它前缀的方法名使用原名
*/
private static String getGeneralField(Serializable fn) {
SerializedLambda lambda = getSerializedLambda(fn);
String getOrSetMethodName = lambda.getImplMethodName();
final String generalField = StrUtil.getGeneralField(getOrSetMethodName);
return StrUtil.isEmpty(generalField) ? getOrSetMethodName : generalField;
}
/***
* 获取类对应的Lambda
*/
private static SerializedLambda getSerializedLambda(Serializable fn) {
//先检查缓存中是否已存在
SerializedLambda lambda;
try {
//提取SerializedLambda并缓存
Method method = fn.getClass().getDeclaredMethod("writeReplace");
method.setAccessible(Boolean.TRUE);
lambda = (SerializedLambda) method.invoke(fn);
} catch (Exception e) {
throw new IllegalArgumentException("获取SerializedLambda异常, class=" + fn.getClass().getSimpleName(), e);
}
return lambda;
}
}
用反射获取实体类get方法的字段名称
最新推荐文章于 2024-06-14 15:02:13 发布