Skip to content
Advertisement

When using javassist anonymous inner class how to access instance variables of outer class?

Below is the anonymous inner class definition:

JavaScript

Below is the running example:

JavaScript

I want to redefine the body of the run method, but I cannot access the instance variables of the outer class in the body

Advertisement

Answer

According to the manual, Javassist does not support inner class generation, but claims to support to read and modify them:

  • Inner classes or anonymous classes are not supported. Note that this is a limitation of the compiler only. It cannot compile source code including an anonymous-class declaration. Javassist can read and modify a class file of inner/anonymous class.

I guess the compiler support ends where you want to do use inner-class-specific syntactic sugar in source code compiled by Javassist, though. A simple workaround would be to use “sacred knowledge” as follows:

JavaScript

Oh look, this$0! Let us try that:

JavaScript

Now we get the console output:

JavaScript

I do not know, how stable and reliable this workaround is across Java releases and compiler flavours.

P.S.: If you change the anonymous inner class to a lambda, the class file looks completely different and you are lost again. I found nothing in the Javassist repository even mentioning lambdas, only a few open issues reporting problems.


Update: I created Javassist issue #358 in order to track this.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement