Issues with generic type detection of SAM types implemented using lambdas

Oliver Gierke ogierke at
Fri Dec 23 11:22:59 UTC 2016

Hi all,

Lambda based implementations of SAM types currently don't support inspecting the type for generic type parameters. This can cause unexpected surprise as some high-level API taking a SAM type as parameter is usually an indicator to users, that they can be used with Lambdas. If the object passed in is then inspected for generic types somewhere down the call stack this causes issues. Handing in a dedicated implementation of the SAM type is a workaround bit I think that's highly confusing and can be a source of errors hard to understand and debug.

I've added an example below.


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


		// 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


		// 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;;
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 841 bytes
Desc: Message signed with OpenPGP using GPGMail
URL: <>

More information about the compiler-dev mailing list