Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to generate an inner class of a class to compile with an annotation processor?

I am wondering if it would be possible to generate a class, via an annotation processor, that would be an inner class of a class to be compiled.

For instance, while compiling class A, generate class A$Foo. I wonder if there is a trick that could be used or not. I got the feeling that it might be possible to generate some source that will be compiled in the same byte code as an inner class would. And, at compile/runtime, the JVM would take it for an inner class, and allow accessing outer class private fields.

The idea behind that question, which is not a noobie question, though it may look more or less technical, is to be able to use the private visibility modifier for annotated fields like Dagger, ButterKnife, etc. The private modifier allowing to detect unused fields more easily, whereas package private protection hides them.

Or is there any workaround, any way to get the best of both words ?

like image 572
Snicolas Avatar asked May 15 '15 06:05

Snicolas


1 Answers

Given your use case, no.

An inner class is a normal Java class, living in a different .class file. When compiled, a hidden constructor param is added to the inner class constructor. Private fields in the outer class are made accessible by adding hidden accessor methods in the outer class. All of this happens at compile time.

The JVM has nothing to do with that. If you generate a class that "looks like an inner class of another class", that won't make the outer class fields accessible.

like image 186
Pierre-Yves Ricau Avatar answered Sep 22 '22 15:09

Pierre-Yves Ricau