有时候需要获取对象的属性名称,但是又不想写死,就可以用lambda获取。
直接上代码
1.实现一个自定义的SFunction类
import java.io.Serializable;
import java.util.function.Function;
@FunctionalInterface
public interface SFunction<T, R> extends Function<T, R>, Serializable {
}
2.实现PropertyNameExtractor工具类
public class PropertyNameExtractor {
private PropertyNameExtractor() {
}
// 获取属性名称的方法
public static <T, R> String getPropertyName(SFunction<T, R> getter) {
try {
// 获取序列化的Lambda
Method writeReplace = getter.getClass().getDeclaredMethod("writeReplace");
writeReplace.setAccessible(true);
SerializedLambda lambda = (SerializedLambda) writeReplace.invoke(getter);
// 从方法名中解析出属性名
String methodName = lambda.getImplMethodName();
if (methodName.startsWith("get")) {
methodName = methodName.substring(3); // 去掉 "get"
} else if (methodName.startsWith("is")) {
methodName = methodName.substring(2); // 去掉 "is"
}
// 将首字母小写以符合JavaBean规范
return Character.toLowerCase(methodName.charAt(0)) + methodName.substring(1);
} catch (Exception e) {
throw new RuntimeException("Failed to extract property name from getter", e);
}
}
public static void main(String[] args) {
// 使用方法引用 User::getName 来获取属性名称
String propertyName = PropertyNameExtractor.getPropertyName(UserDO::getName);
System.out.println("Property name: " + propertyName); // 输出:Property name: name
}
}
3.使用方法
// 使用方法引用 User::getName 来获取属性名称
String propertyName = PropertyNameExtractor.getPropertyName(UserDO::getName);