我有几节课:
public class TextContent {
private String externalId;
}
public class ImageContent {
private String externalImageId;
}
public static void validateImageInput(List<ImageContent> imageAssets, String requestId) {
if(CollectionUtils.isEmpty(imageAssets)) {
throw some Error;
}
Set<String> uniqueIds = imageAssets.stream().map(ImageContent::externalImageId).collect(Collectors.toSet());
if(uniqueIds.size() != imageAssets().size()) {
throw some Error;
}
//Do some processing
}
public static void validateTextInput(List<TextContent> textAssets, String requestId) {
if(CollectionUtils.isEmpty(textAssets)) {
throw some Error;
}
Set<String> uniqueIds = textAssets.stream().map(ImageContent::externalId).collect(Collectors.toSet());
if(uniqueIds.size() != textAssets().size()) {
throw some Error;
}
//Do some processing
}
如您所见,这两个类的验证部分是相同的。我想尝试使这成为一种通用方法。为了那个原因:
public static void validateInput(List<?> assets, String requestId, Supplier<String> mapper) {
if(CollectionUtils.isEmpty(assets)) {
throw some error;
}
Set<String> uniqueIds = assets.stream().map(x -> mapper.get()).collect(Collectors.toSet());
if(uniqueIds.size() != assets().size()) {
throw some Error;
}
}
然后调用它:
public static void validateAllInputs(List<ImageContent> imageAssets, List<TextContent> textAssets, String requestId) {
validateInput(imageAssets, requestId, ImageContent::externalImageId);
validateInput(textAssets, requestId, TextContent::externalId);
doSomeProcessingWithText(textAssets, requestId);
doSomeProcessingWithImage(imageAssets, requestId);
}
但我得到一个错误说Non static method cannot be referenced from static context.
编辑:我尝试的另一个选项是 using Function
,即我传入 a<TextContent, String> mapper
并在我的流中使用.map(x -> mapper.apply(x)
. 但是,当我尝试将它传递给函数时,validateInputs(textAsset, requestId, TextContent::externalId)
我得到了同样的错误Non static method cannot be referenced from static context.