How can I get Java 8 Lambda from pedigree, clazz and frontend?

I have a class that takes a generic

public class Publisher<T extends Storable> {
    ...
} 

      

Objects of classes that extend Storable can be "published" (processed by this class).

In the constructor, I also get information about the specific class that this instance is if the Publisher should handle

public Publisher(Class<T> clazz) {
    ...
}

      

In this constructor, I check if the class implements "Localized". If so, I want to store the lambda in the method defined in the localized interface (in this example "getLocale ()"). The reason I want the lambda to be for backward compatibility reasons is not to focus on this design decision.

public class Publisher<T extends Storable> {

    private Function<T, Locale> localeGetter;

    public Publisher(Class<T> clazz) {
        if (Localized.class.isAssignableFrom(clazz)) {
            this.localeGetter = ???????;
        }
    }
}

      

All the information should be there, I think, to set my lambda, but I can't figure out how to code it. Is it possible?

Best wishes Andreas

+3


source to share


1 answer


Remember how you would perform an operation with regular code, and then put that code in a lambda expression:

if (Localized.class.isAssignableFrom(clazz)) {
    this.localeGetter = t -> ((Localized)t).getLocale();
}

      



Due to type erasure, you cannot take advantage of the fact that the class was parameterized with a type for T

that implements Localized

, however, it doesn't hurt much even if you could, as a result the code would contain the same type at the byte code level.

The only way to get around this is to let the calling constructor provide the function (add a parameter Function<T, Locale>

). But depending on the number of different subscribers, that is not necessarily a simplification.

+3


source







All Articles