2

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"

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
ST-DDT
  • 2,615
  • 3
  • 30
  • 51

1 Answers1

1

You're not doing anything wrong (with regards to getGenericInterfaces).

The class Foo contains its full type information in its declaration. That is made available to its corresponding Class object.

The same cannot be said of the dynamic "proxy" classes generated for the instances resulting from the method references. The inferred generic type arguments are not kept in the bytecode that eventually generates the instance.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724