Skip to content

Instantly share code, notes, and snippets.

@odrotbohm
Last active January 28, 2023 09:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odrotbohm/1283b59dc9a22b74170378a8a94d9019 to your computer and use it in GitHub Desktop.
Save odrotbohm/1283b59dc9a22b74170378a8a94d9019 to your computer and use it in GitHub Desktop.
Lambda type detection sample

Lambda type detection sample (or the inability to do so)

This sample shows how code taking SAM types is not able to detect generic type parameters on Lambda-based implementations of SAM types.

This is kind of a bad situation as implementations that take SAM types and try to use the type information that’s prefectly available on an regular implementation now all of a sudden is not if the caller — potentially a couple of stack frames above — assumed the ability to use a Lambda due to some API exposing a SAM type.

public class LambdaTypeDetectionSample {
public static void main(String[] args) {
Function<Integer, String> lambdaFunction = i -> i.toString();
Function<Integer, String> oldschoolFunction = new Function<Integer, String>() {
public String apply(Integer t) {
return t.toString();
}
};
printTypeArguments(oldschoolFunction);
// Yields:
// java.util.function.Function<java.lang.Integer, java.lang.String> is a class sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
// class java.lang.Integer
// class java.lang.String
printTypeArguments(lambdaFunction);
// Yields:
// interface java.util.function.Function is a class java.lang.Class
}
private static void printTypeArguments(Function<?, ?> function) {
Type type = function.getClass().getGenericInterfaces()[0];
System.out.println(type + " is a " + type.getClass());
if (type instanceof ParameterizedType) {
ParameterizedType functionInterface = (ParameterizedType) type;
Arrays.stream(functionInterface.getActualTypeArguments()).forEach(System.out::println);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment