开发者

How to Parse multiple classes from groovy file

开发者 https://www.devze.com 2023-01-01 02:09 出处:网络
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\"))

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开发者_JAVA技巧 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
0

精彩评论

暂无评论...
验证码 换一张
取 消