Search code examples
scalagroovyscopegroovyshell

How do you access variables of super class of passed class in Groovy Script Engine?


I'm dynamically running groovy scripts from scala. And there are some instances of some class passed to groovy scripts via setProperty(). For example, say you have a class named TestA and class TestB inherits class TestA. And you are passing an instance of class B to groovy script like this

setProperty("testB", testB) // testB is an instance of class TestB

and running the groovy script, I can access variables declared in TestB. but when I try to access variables of TestA, which is super class of TestB, the groovy gives an error saying " No such property for class".

I can still call methods of both TestA and TestB from the given instance. So if you just write setter and getter, I can access to TestA's variables but I don't want to do it.

Is there anyway to access TestA's variables without using setter/getter? like using Expando or something?


Solution

  • Since you don't want to write the getters/setters yourself (which would be ugly boilerplate in Scala), you can simply add the scala.reflect.BeanProperty annotation (or scala.reflect.BooleanBeanProperty) to any fields you'd like to access from another JVM language. This will give you a more accessible API.

    @scala.reflect.BeanProperty // generates getStatus() and setStatus() methods
    var status = ""