beanshell2 icon indicating copy to clipboard operation
beanshell2 copied to clipboard

Anonymous inner classes and referencing member variables

Open GoogleCodeExporter opened this issue 10 years ago • 0 comments

If create an anonymous inner class (say "Inner") inside another class 
declaration (say "Outer"), and from within this inner class try to refer to a 
member variable of "Outer", it breaks with a "bsh.EvalError: Error constructing 
inner class instance: java.lang.reflect.InvocationTargetException"

To be specific, it breaks, if "Inner" is extending a class, but works if 
"Inner" is simply implementing an interface.

Here is a script to reproduce the problem. It should print "Apple", but throws 
an exception instead:
---------------------------------------

class Inner { // Example works if change to interface

}

class Outer {
  String fruit = "Apple";

  Outer() {
    new Inner() {
      {
        System.out.println(fruit);
      }
    };
  }
}

new Outer();
---------------------------------


What version of the product are you using? On what operating system?
bsh 2.2.0 on Mac OSX


Please provide any additional information below:
This problem makes it hard to write truly object oriented scripts. I have to 
make the member variables global variables in order to be able to refer to them 
from anonymous inner classes.



Original issue reported on code.google.com by [email protected] on 27 Oct 2013 at 10:24

GoogleCodeExporter avatar Apr 22 '15 19:04 GoogleCodeExporter