JDK 8 - Lambda - Reflection issues

Pavel Bucek pavel.bucek at oracle.com
Wed Mar 12 18:12:24 UTC 2014


Hello all,

I have an issue with getting generic parameter when using lambdas. I can 
get the type when using anonymous classes.

code sample will be more descriptive than anything I would say, so.. :

public class Main {

     public static interface A<T> {
         public void method(T param);
     }

     public static void main(String[] args) {

         final A<Main> anonClass = new A<Main>() {
             @Override
             public void method(Main param) {
                 System.out.println("234");
             }
         };

         final A<Main> lambda = param -> System.out.println("234");

         //following does not help.
         // final A<Main> lambda = (A<Main>)param -> 
System.out.println("234");


         // output: Main.Main$A<Main>
         System.out.println("$ " + 
anonClass.getClass().getGenericInterfaces()[0]);

         // output: interface Main$A          ### generic type info is 
already lost (no <Main>)
         System.out.println("# " + 
lambda.getClass().getGenericInterfaces()[0]);

         // parameterized type from annon class
         final Type t = 
((ParameterizedType)anonClass.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0];
         System.out.println("$ " + t);

         // parameterized type from lambda
         System.out.println("# " + "???");
     }
}

I was not able to find any useful documentation or article about this, 
so sorry if this is something common - feel free to RTM me (with 
relevant link please).

Thanks and regards,
Pavel


More information about the jdk8-dev mailing list