简体   繁体   English

如何从 groovy 文件中解析多个类

[英]How to Parse multiple classes from groovy file

Is there a way to parse all all the classes in a groovy script?有没有办法解析 groovy 脚本中的所有类? To Parse ONE class right now:现在解析一个 class:

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

MainApp.groovy: MainApp.groovy:

class MainApp {
   def doIt() {}
}

class OtherMainApp {
  def doTheRest() {}
}

This will return only MainApp.这将只返回 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其中 clazz 包含将包含 MainApp class 和 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由于我正在构建的应用程序的性质,groovyc 命令无济于事

Thanks,谢谢,

Federico费德里科

No can do:不可以:

https://issues.apache.org/jira/browse/GROOVY-3793 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.直到 Groovy 修复了该错误。

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.自从提出和回答这个问题以来已经 12 年了,但是当我试图弄清楚如何做同样的事情时,它出现在我的谷歌搜索结果的顶部。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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