3

I recently heard that using Java inner classes in a class that enclose sensitive information is causing the private data of the class to be changed to protected at the bytecode level (meaning that any other class of the package may access it).

As I do not have any expertise in bytecode reading I would like to know if it is true, and get some explanation of this problem.

7

The problem is that there is no notion of inner classes at the bytecode level. Each inner class is compiled to a separate class with no special privileges compared to any other class in the same package.

So in order to support the functionality of inner classes, the compiler has to add getter methods behind the scenes. Every time you access a field in the outer class from the inner class, the compiler needs to generate a getter in the outer class. However, these getters cannot be private because then nothing could call them! Therefore, the getter is always at least protected, meaning any class in the same package can access it.

Update: Java 11 added a new bytecode feature to address this issue, so this does not apply to recent versions of Java.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.