« HttpUnit and JavaScript | Main | HTTPS testing with jWebUnit »

BeanShell and finally

Trying to use BeanShell 2.0b4 to allow on-the-fly database driven Java interface implementations I was getting an odd error when trying to call a method on the interface. There weren't any errors instantiating the interface only when I called the method. The error was something like:

Caused by: Incorrect type returned from method: validate
Can't assign void value to com.neophi.ValidateResult:
Can't assign void value to com.neophi.ValidateResult:
at Line: -1 : in file: <Called from Java Code> : <Compiled Java Code>

The root cause was that the version of BeanShell being used doesn't fully support all Java constructs. In particular this sample code will cause the above error:

public ValidateResult validate(String email, String password)
{
try {
return new ValidateResult();
} finally {
// something that must always happen
}
}

In order to work in BeanShell the method must be rewritten as such:

public ValidateResult validate(String email, String password)
{
ValidateResult validationResult = null;
try {
validationResult = new ValidateResult();
} finally {
// something that must always happen
}
return validationResult;
}

Hopefully this will spare someone else from getting a headache.

Comments

Saved me some headache, thanks. My code had no finally block, but it did return halfway through a method. This problem vanished if I created the result object at the start and returned it at the end (which, IMO, is the better style anyway).