创建接口
public interface FieldGetter<T, R> extends Function<T, R>, Serializable {
@SneakyThrows
default String getFieldName() {
String methodName = getMethodName();
if (methodName.startsWith("get")) {
methodName = methodName.substring(3);
}
return CharSequenceUtil.lowerFirst(methodName);
}
@SneakyThrows
default String getMethodName() {
return getSerializedLambda().getImplMethodName();
}
@SneakyThrows
default Class<?> getFieldClass() {
return getReturnType();
}
@SneakyThrows
default SerializedLambda getSerializedLambda() {
Method method = getClass().getDeclaredMethod("writeReplace");
method.setAccessible(true);
return (SerializedLambda) method.invoke(this);
}
@SneakyThrows
default Class<?> getReturnType() {
SerializedLambda lambda = getSerializedLambda();
Class<?> className = Class.forName(lambda.getImplClass().replace("/", "."));
Method method = className.getMethod(getMethodName());
return method.getReturnType();
}
}
使用方式
public <T,R> void getFieldInfo(FieldGetter<T, R> fieldGetter) {
System.out.println(fieldGetter.getFieldName());
System.out.println(fieldGetter.getReturnType());
System.out.println(fieldGetter.getMethodName());
}