Groovy中main方法用evaluate加载外部类遇MissingMethodException求助
问题场景
文件内容
sample.groovy(定义Person类):
class Person { String firstName String lastName String getFullName() { return "$firstName $lastName" } def addMarksInSubjects(a, b){ return a+b; } }
runfile.groovy(尝试加载Person类并调用):
// Load the Person class from sample.groovy evaluate(new File('sample.groovy')) class Main { static void main(String[] args) { // Create an instance of Person def person = new Person(firstName: 'Stack', lastName: 'Overflow') // Use the method from the Person class println "Full Name: ${person.getFullName()}" } }
文件夹结构
. ├── runfile.groovy └── sample.groovy
报错信息
Caught: groovy.lang.MissingMethodException: No signature of method: static Person.main() is applicable for argument types: ([Ljava.lang.String;) values: [[]]
Possible solutions: wait(), wait(long), any(), find(), wait(long, int), any(groovy.lang.Closure)
groovy.lang.MissingMethodException: No signature of method: static Person.main() is applicable for argument types: ([Ljava.lang.String;) values: [[]]
Possible solutions: wait(), wait(long), any(), find(), wait(long, int), any(groovy.lang.Closure)
错误原因
Groovy执行脚本时,默认会尝试调用脚本中第一个被加载/定义的类的static main方法作为执行入口。你在脚本顶层用evaluate加载了Person类,Person成为脚本中第一个存在的类,但它没有定义static main方法,因此触发该错误。
解决方法
方法一:将evaluate移至Main类的main方法内部
修改runfile.groovy,把加载Person类的逻辑放到Main类的main方法里:
class Main { static void main(String[] args) { // 在main方法内部加载Person类 evaluate(new File('sample.groovy')) def person = new Person(firstName: 'Stack', lastName: 'Overflow') println "Full Name: ${person.getFullName()}" } }
原理:此时Person类是在Main类的静态上下文里被加载的,Groovy会以Main类的main方法作为执行入口,不会去查找Person类的main方法。
方法二:去掉Main类,直接写成Groovy脚本
简化runfile.groovy,不需要包裹类,直接执行逻辑:
// 加载Person类 evaluate(new File('sample.groovy')) // 创建实例并调用方法 def person = new Person(firstName: 'Stack', lastName: 'Overflow') println "Full Name: ${person.getFullName()}"
原理:Groovy脚本本身可以直接作为执行入口,脚本中的代码会按顺序执行,不会触发对类的main方法查找。
内容的提问来源于stack exchange,提问作者Eerama19

