vendredi 20 avril 2018

Pass field name/type as a parameter to a method in Java

I have a List of LocalizedAttributes

public class LocalizedAttribute<T> {
    T value;
    Locale locale;
}

I have a class which stores the list of the localized attributes;

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

I have a class which has some book related info.

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

I create a bunch of books

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

I add this in an object of class A

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

Now I want to extract list of localized titles, summary separately.

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());
}

Now If I want to get list of summary I need to write the exact same method again except for b.getTitle and so on. Is there a cleaner way to do this?

Aucun commentaire:

Enregistrer un commentaire