How can Java run Groovy script dynamically 2

This is a continue with the previous blog “How can Java run Groovy script dynamically”.

We try to do some complex things inside the groovy script, this time we tried to define a data structure directly inside the script, and see if the GroovyShell can identify it at run time and run correctly

Following are the sample script that passed to the GroovyShell

The code refers to “How to use a Groovy trait to output any class as csv?”

import java.io.ByteArrayInputStream
import java.io.Reader
import java.io.InputStreamReader
import static com.xlson.groovycsv.CsvParser.parseCsv

def sb = StringBuilder.newInstance()

/*
// TEST1 - simple CSV parsing
Reader inputReader = new InputStreamReader(new ByteArrayInputStream(input));
for(line in parseCsv(inputReader,separator:",")){
  // println line
  sb.append(line.attribute1+";"+line.attribute2)
  sb.append("\n")

}

output = sb.toString().getBytes()
*/

// TEST2 - Define data structure inside the dynamic script and gets output
def m = new MeetupMember()
m.name = "Sergio del Amo"
m.locality = "Guadalajara"
m.twitter = "https://twitter.com/sdelamo"
m.facebook = null
m.tumblr = null
m.imageUrl = "http://photos4.meetupstatic.com/photos/member/c/d/6/b/member_254392587.jpeg"
m.website = "http://www.meetup.com/es-ES/Warsaw-Groovy-User-Group/members/200767921/"

output = m.asCSV().getBytes()

// Following are the data structure definition
// You can see that this part is at the end of the script
// But GroovyShell handle it correctly
trait TraitAsCSV {
// manually provide the header to make sure the csv output is in the expected sequence
   List<String> propertyNames() {
        return ["name","locality","twitter","facebook","tumblr","background","imageUrl","website"]
    }

    String csvHeaders() {
        propertyNames().join(delimiter())
    }

    String asCSV() {
        def str = ""
        def arr = []
        for(def propName in propertyNames()) {
            def v = this."$propName"
            arr <<  (v ?: "")
        }
        arr.join(delimiter())
    }

    static String delimiter() {
     ";"
    }
}
class MeetupMember implements TraitAsCSV {
    String name
    String locality
    String twitter
    String facebook
    String tumblr
    String background
    String imageUrl
    String website
}