What is "inner class emulation" in Java?
Asked Answered
G

2

6

just found this bit, while reading eclipse JDT's documentation:

IMethodBinding.getParameterTypes(): . . . Note: The result does not include synthetic parameters introduced by inner class emulation.

I can't find any reference to inner class emulation in JLS... Anyone knows what this emulation is? Throwing an example, would help as well. :)

Glad answered 18/12, 2010 at 4:36 Comment(0)
M
4

I think that the Eclipse documentation writer being a little bit loose with the terminology. As far as the JLS is concerned, an inner class is an inner class and doesn't need to be emulated.

However, there is a bit of trickiness in the way that inner classes get implemented by a typical JVM, and this is where the synthetic constructor parameters come into the equation. What is going on is that the JVM implements classes the same whether they are nested or not. There are no special bytecodes for referring to variables in enclosing classes, so the compilers generate code that fetch them via the synthetic attributes.

More details may be found in the original Sun Java 1.1 Inner Classes Specification.

Miscall answered 18/12, 2010 at 5:12 Comment(2)
Thanks. I agree with you. Additional info I found in retrologic.com/innerclasses.doc10.html that complements what you said: A synthetic field pointing to the outermost enclosing instance is named this$0. The next-outermost enclosing instance is this$1, and so forth. (At most one such field is necessary in any given inner class.) . . . . All these synthetic fields are initialized by constructor parameters . . . . All such constructor parameters are deemed to be synthetic.Glad
@John - that's the same document ... published in a different place.Miscall
S
2

I suspect that “inner class emulation” is meant to be how the compiler generate the byte code for inner classes.
There is no inner class support at virtual machine level (at least when they got introduced). The compiler must generate byte code as for a normal class when compiling an inner class. Adding a reference to the outer class instance, for example:

public class Outer {

    class Inner {
        @Override
        public String toString() {
            return "Inner";
        }
    }
}

the Inner class get compiled to something similar to:

class Outer$Inner {
    final Outer this$0;  // the instance of the outer class

    Outer$Inner(Outer outer) {
        super();
        this$0 = outer;
    }

    public String toString() {
        return "Inner";
    }
}
Saddlecloth answered 18/12, 2010 at 10:45 Comment(1)
Yes, the reference to the outer class is a synthetic fields that is initialized by synthetic constructor parameters.Glad

© 2022 - 2024 — McMap. All rights reserved.