Skip to content

[Compiler] Reflection fails due to class file's EnclosingMethod attribute incorrectly pointing to lambda implementation #975

@Marcono1234

Description

@Marcono1234

Version

Eclipse Compiler 3.33.0
(Maven: org.eclipse.jdt:ecj:3.33.0)

Description

Preconditions:

  • a generic method M of a local class ...
  • contains a lambda expression ...
  • which creates an anonymous class C of a generic class ...
  • which captures a type variable from M

In that case reflection erroneously returns null as type argument for C.
If any of the above is changed, e.g. not using a lambda, or not using a local class, then it looks like this cannot be reproduced.

Have reported this for the Eclipse compiler because the same code seems to work as expected when compiling and running using JDK 17 (though same error occurs with JDK 11, see JDK-8306438). But maybe this is actually a bug in the Java reflection library.

Reproduction steps

  1. Create a file called Test.java with the following content
    import java.lang.reflect.*;
    
    class Test {
        static class Capturing<T> {
            protected Capturing() {
                ParameterizedType paramT = (ParameterizedType) getClass().getGenericSuperclass();
                Type t = paramT.getActualTypeArguments()[0];
    
                if (t instanceof TypeVariable) {
                    System.out.println("Found expected type");
                } else {
                    throw new AssertionError("Unexpected type: " + t);
                }
            }
        }
    
        static void run(Runnable r) {
            r.run();
        }
    
        public static <T> void main(String... args) {
            class Local {
                <M> void runTest() {
                    run(() -> new Capturing<M>() {});
                }
            }
    
            new Local().runTest();
        }
    }
  2. Compile the class with the Eclipse compiler
    java -jar ./ecj-3.33.0.jar -17 ./Test.java
    
  3. Try to run the compiled class using Java 17
    java Test
    ❌ Bug: It fails with AssertionError: Unexpected type: null

Metadata

Metadata

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions