saga
saga

Reputation: 2113

What is the use of InnerClass Attribute in a classfile?

I understand that inner classes and anonymous classes are compile time constructs provided by java compiler. If that's the case, why does a classfile have to contain info about the inner classes declared inside it. The JVM specs state that:

The InnerClasses attribute must be recognized and correctly read by a class file reader in order to properly implement the Java SE platform class libraries

I'm having trouble understanding what this statement means. Can someone elaborate on this statement?

Upvotes: 2

Views: 363

Answers (2)

Octavian R.
Octavian R.

Reputation: 1271

That information is necessary from Java11 and its related to the way of how the inner classes access the methods and the variables of the outer class.

You can read more about this here: openjdk.java.net/jeps/181

EDIT:

Let's considering the following example:

public class Outer {

    public void print() {
        System.out.println("Hello");
    }

    private class Inner {

        public Inner() {
            print();
        }
    }
}

If you compile this class with java8 (left side) and java11 (right side) you can see the following differences:

enter image description here enter image description here

Upvotes: 1

Antimony
Antimony

Reputation: 39451

There is a lot of metadata stored in the bytecode about Java level features with no direct effect on bytecode execution. This is useful for several reasons. First off, Java has reflection libraries which provide access to this information, so it must be available to the JVM at runtime somehow. Second, it allows you to compile against binary only libraries.

Another example of a "useless" feature are the throws clauses (stored as an optional attribute in the bytecode). These are needed so you can compile against classfiles without the source but have no effect on the execution of bytecode.

Upvotes: 3

Related Questions