Inner classes MUST have a reference to their outer class. This is implied by the JVM. In the following example, the call to new InnerClass()
translates to new InnerClass(this)
. OuterClass
instance is stored in the $outer
field in the inner class, which can be accessed using this OuterClass.this
syntax.
class OuterClass { val str = "abcde"; val inner = new InnerClass(); class InnerClass { def printStr() { println(OuterClass.this.str); } } }
To build a new InnerClass instance using reflections, you must have a reference to the OuterClass instance. To create a new instance, follow these steps:
val outer = new OuterClass; val newInner = outer.inner.getClass.getDeclaredConstructor(classOf[OuterClass]) .newInstance(outer);
In addition, I would say that creating a new inner class using reflections sounds like a pretty bad coding practice. Only OuterClass should ever see InnerClass instances and therefore should be prepared for any situation where it might need to create a new InnerClass instance. If other classes have InnerClass visibility, then you need to rebuild it into your class.
Dunes source share