lundi 30 novembre 2015

Get generic type from a Function

I would like to get the result type of a java.util.function.Function. (If the return type is already Optional then I don't have to do anything, but otherwise I have to wrap it in Optionals and for obvious reasons I don't want to wrap it twice.

Here is my example code:

public static void main(String[] args) {
    printType(Integer::parse);
    printType(new Foo());
    printType(Functions::tryParseInt);
}

public static void printType(Function<String, ?> function) {
    System.out.println(function.getClass());
    System.out.println(function.getClass().getGenericInterfaces()[0]);
    if (!returnsOptional(function)) function = function.then(Optional::ofNullable);
    [...]
}

private static class Foo implements Function<String, Integer> {
    @Override
    public Integer apply(String t) {
        return Integer.parse(t);
    }

}

public static Optional<Integer> tryParseInt(String a) {
    return Optional.empty();
}

I get this as result:

class my.util.Functions$$Lambda$1/1705736037
interface java.util.function.Function
class my.util.Functions$Foo
java.util.function.Function<java.lang.String, java.lang.Integer>
class my.util.Functions$$Lambda$3/764977973
interface java.util.function.Function

but actually I would like get java.lang.Integer or java.util.Optional from the method. For second one this works using get getGenericSuperClass() + ParameterizedType, but not for the other two? What am I doing wrong?

java version "1.8.0_51"





Aucun commentaire:

Enregistrer un commentaire