我正在使用 LambdaMetaFactory 来公开 getter。我有一个包含许多字段的 POJO,但我不知道要填充哪些字段。我试图避免扩展 if 语句和反射。
所以这是我 POJO 的一个片段:
@Data
@Builder
public class MyPojo {
private String email;
private String firstName;
private String lastName;
private String zipCode;
private String city;
private String street;
private String country;
...
}
这是我从所有 getter 中获取我的值的方法:
public static String getValueFromGetterMethodName(String fieldName, MyPojo myPojo) {
String methodName = constructGetterMethodName(fieldName);
final MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType getChangeDataMethodType = methodType(String.class, MyPojo.class);
try {
final CallSite site = LambdaMetafactory.metafactory(lookup, "apply", methodType(Function.class),
methodType(Object.class, Object.class),
lookup.findVirtual(MyPojo.class, methodName, methodType(String.class)),
getChangeDataMethodType);
Function<MyPojo, String> getterFunction = (Function<MyPojo, String>) site.getTarget()
.invokeExact();
return getterFunction.apply(myPojo);
}
catch (Throwable e) {
log.error("Error getting getter method ref: " + e.getMessage());
e.printStackTrace();
}
return null;
}
问题是这里的这一行:
Function<MyPojo, String> getterFunction = (Function<MyPojo, String>) site.getTarget()
.invokeExact();
产生 Unchecked Class Cast 警告。我知道我们应该避免这些。这段代码工作得很好。我不确定如何更改它以避免类强制转换异常。CallSite 不接受参数。