Anonymous inner class ordering
Asked Answered
D

0

6

I have a code snippet similar to the following in my project:

public static void main(final String[] args) {
    System.out.println("Hello world");
    final TypeReference<String> tr1 = new TypeReference<>() {};
    final Runnable r = () -> {
        System.out.println("Running");
        final TypeReference<String> tr = new TypeReference<>() {};
        System.out.println(tr);
    };
    new Thread(r).start();
}

This is present in eclipse that runs with Java 11. Now, when eclipse compiles this class, it generates the following files:

TestAnon.class
TestAnon$2.class
TestAnon$3.class

As it has got two anonymous inner classes, it makes sense to have two different class files with $. However, the postfixes are $2 and $3 instead of $1 and $2. Any specific reason for generating class files in this order (and skipping $1)?

P.S. When I compile the class on command line, it generates classes files in correct order.

Dampproof answered 20/1, 2020 at 11:45 Comment(7)
Is there a reason why you care? This is an implementation detail that you should not rely uponTyrus
I am mocking one of these classes in tests and it fails with error message saying it can't find the class with $1.Dampproof
By doing so, you will create tests which are brittle. You are creating a tight coupling between order in which anonymous classes are declared and the success of your test. Someone could refactor your class and add an additional anonymous class before yours and break the test. You should look for a way to not rely upon this.Tyrus
I think one of the reason why this TestAnon.class does not have $1 is that it is class which you actually runing(?) so to make it simple. But if you try this code run from other class, not main I think it will generate $1 as well. Not sure just guessing.Broom
Note that Eclipse has its own compiler which may make different choices about things like this.Huntsman
Your inner classes sound like they should be private to the outer class. Your test class should not need them. I'd rethink either the class or the test design.Climactic
Can not reproduce, neither with javac nor with Eclipse. Either, it is very version specific or the code doesn’t look like you’ve posted.Emikoemil

© 2022 - 2024 — McMap. All rights reserved.