简体   繁体   中英

How to Parse multiple classes from groovy file

Is there a way to parse all all the classes in a groovy script? To Parse ONE class right now:

java.lang.Class clazz = groovyClassLoader.parseClass(new File("MainApp.groovy"))

MainApp.groovy:

class MainApp {
   def doIt() {}
}

class OtherMainApp {
  def doTheRest() {}
}

This will return only MainApp.

I would like something like this:

java.lang.Class[] clazz = groovyClassLoader.parseClass(new File("MainApp.groovy"))

where clazz contains will contain both MainApp class and OtherMainApp class

Basically I want to be able to extract all the declared classes in a script.

Because of the nature of the app that I'm building groovyc command won't help

Thanks,

Federico

No can do:

https://issues.apache.org/jira/browse/GROOVY-3793

You could do it yourself though: you could parse the class yourself (just count the {} pairs), dump it out to a new file, and away you go. Ugly? yes. Painful? Very. Possible? Maybe. Better solution? Not until Groovy fixes the bug.

It's been 12 years since this question was asked and answered, but it arrived at the top of my Google results when I was trying to figure out how to do the same thing.

This ended up working for me:

def loader = new GroovyClassLoader()
loader.parseClass(new File("Company.groovy"))
Class Location = loader.loadClass("tk.vallerance.spacecompanies.models.Location")
Class Event = loader.loadClass("tk.vallerance.spacecompanies.models.Event")
Class Company = loader.loadClass("tk.vallerance.spacecompanies.models.Company")

println Location
println Event
println Company

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM