BeanShell Troubles

I had to fight with BeanShell again today. ¬†For some reason, incrementing a simple int doesn’t work if the int is outside of the scope of the method that increments it. It works just fine if the integer is modified in-scope; that is, the same method, or in the main body of the beanshell script.

This doesn’t work:

int testInt = 0;

void someUtilityMethod(String var, String var2) {
    testInt++;
}

// main body
log.debug("testInt=" + testInt); // output is 0
someUtilityMethod("one", "two");
log.debug("testInt=" + testInt); // output is still 0

Go ahead, try it. This, however, does work:

int[] testInt = new int[1];
testInt[0] = 0;

void someUtilityMethod(String var, String var2) {
    testInt[0]++;
}

// main body
log.debug("testInt=" + testInt[0]); // output is 0
someUtilityMethod("one", "two");
log.debug("testInt=" + testInt[0]); // output is 1

Weird, huh? I suspect the second case works simply because arrays are Objects in java. BeanShell seems to do OK with objects, but totally screws the pooch on primitives.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.