0

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.

ic10503
  • 131
  • 4
  • 16
  • Please add the code you have tried and how it failed (e.g. errors, stacktraces, logs, ...) so we can improve on it. Assuming those scripts where meant to be run somewhere else and you are trying to make it work somewhere else, it would help to be specific about the old and new env you ran it etc. – cfrick Nov 03 '21 at 14:45
  • 1
    shouldn't you be initializing the `a` before null-checking it? what's the point of the missing property in your case? – injecteer Nov 04 '21 at 09:42

0 Answers0