Java Groovy - 主要方法放置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23717406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Groovy - Main method placement
提问by user2475310
Here is my code:
这是我的代码:
class cat {}
class dog {
static void main(String[] args) {}
}
When compiled groovy says I do not have a main method. But when I get rid of the cat class:
编译 groovy 时说我没有 main 方法。但是当我摆脱 cat 课时:
class dog {
static void main(String[] args) {}
}
Its valid. I thought, as long as I had the main method in anyclass the code was valid, but I am wrong. Can someone explain why I can not have more than one class when the main method resides in one of the classes?
其有效。我想,只要我在任何类中有 main 方法,代码就是有效的,但我错了。有人可以解释为什么当主要方法驻留在其中一个类中时我不能有多个类吗?
回答by dmahapatro
You can have more than one class, but the class defined first has to have the main method implementation. Normally when run as a script, the script is executed in run()
method.
您可以拥有多个类,但首先定义的类必须具有主要方法的实现。通常当作为脚本运行时,脚本在run()
方法中执行。
In case you have a class defined, then the name of the class is used as the name of the script. In case there are more than one public class, then the runnable implementation has to be part of the first defined class. Below should work:
如果您定义了一个类,则该类的名称将用作脚本的名称。如果有多个公共类,那么可运行的实现必须是第一个定义的类的一部分。下面应该工作:
class Dog {
static void main(String[] args) {
println "hello"
}
}
class Cat {}
You can get a clear picture when you inspect AST in groovy console.
当您在 groovy 控制台中检查 AST 时,您可以获得清晰的图片。