将字段名称/类型作为参数传递给Java中的方法

时间:2018-04-20 08:24:44

标签: java oop design-patterns java-8

我有一个LocalizedAttributes列表

public class A {
    .
    .
    private List<LocalizedAttribute> localizedAttributes;
}

我有一个存储本地化属性列表的类;

public class B {
    private String title;
    private String summary;
    private List<String> authors;
    private List<Map<String, String>> publisherRoles;
}

我有一个课程,里面有一些书籍相关信息。

B bookRelatedInfo1 = new B(); ///fill in values;
B bookRelatedInfo2 = new B(); ///fill in values;
B bookRelatedInfo3 = new B(); ///fill in values;

我制作了一堆书

A.setLocalizedAttributes(ImmutableList.of(
            new LocalizedAttribute(bookRelatedInfo1, new Locale("US")),
            new LocalizedAttribute(bookRelatedInfo2, new Locale("DE")),
            new LocalizedAttribute(bookRelatedInfo3, new Locale("JP"))
))

我将它添加到A类的对象中

getLocalizedTitles(List<LocalizedAttribute> localizedAttributes) {
    return localizedAttributes.stream()
        .map(localizedAttribute -> {
            Locale locale = localizedAttribute.getLocale();
            B b = (B) localizedAttribute.getValue();
            return new LocalizedAttribute(b.getTitle(), locale);
        })
        .collect(Collectors.toList());
}

现在我想分别提取本地化标题列表,摘要。

b.getTitle

现在如果我想获得摘要列表,我需要再次编写完全相同的方法,除了{{1}}等等。有更清洁的方法吗?

1 个答案:

答案 0 :(得分:4)

您可以将Function<B,T>传递给该方法:

<T> List<LocalizedAttribute<T>> getLocalizedAttributes(List<LocalizedAttribute<B>> localizedAttributes, Function<B,T> mapper) {
    return localizedAttributes.stream()
        .map(localizedAttribute -> {
            Locale locale = localizedAttribute.getLocale();
            B b = localizedAttribute.getValue();
            return new LocalizedAttribute<T>(mapper.apply(b), locale);
        })
        .collect(Collectors.toList());
}

可以简化为:

<T> List<LocalizedAttribute<T>> getLocalizedAttributes(List<LocalizedAttribute<B>> localizedAttributes, Function<B,T> mapper) {
    return localizedAttributes.stream()
        .map(la -> new LocalizedAttribute<T>(mapper.apply(la.getValue()), la.getLocale()))
        .collect(Collectors.toList());
}

然后你可以把它称为:

List<LocalizedAttribute<String>> titleList = getLocalizedAttributes(list,B::getTitle);

List<LocalizedAttribute<String>> summaryList = getLocalizedAttributes(list,B::getSummary);