I have a groovy script that may have some undefined properties:
// a new file say: test.groovy
import Comp;
if (a == null) { // a is a missing property
return new obj();
}
def objComp = new Comp(name: 'tim')
return objComp
I want to execute test.groovy and extract the JSON format of objComp
using
new JsonBuilder(objComp).toPrettyString()
which can print something like
{
name: 'tim'
}
However I keep getting groovy.lang.MissingPropertyException
because of the missing property a
. I tried to use a separate class that extends Expando, but I get the same Exception:
class MyClass extends Expando {
def myMethod() {
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
result = shell.evaluate 'def test() { "eval test" }; return test()' // works fine
String fileContent = new File("/path/to/test.groovy").text
result = shell.evaluate(fileContent) // leads to MissingPropertyException
}
}
I was hoping using Expando would fix the MissingPropertyException
, but it doesn't.