Scala - “同伴包含其自己的主要方法,这意味着不能生成静态转发器”的含义
给定以下类及其伴生对象:
class B extends A
object B extends B
其中 A 是另一个文件中的抽象类:
abstract class A {
def main(args: Array[String]): Unit = println("hey")
}
上述代码使用 sbt 程序集插件打包到 uber-jar 中,其中入口点是 object B
main从类B
继承的方法。
上面的效果很好。它运行了。完全没问题。
然而,sbt不断警告:
[warn] B has the main method with parameter type Array[String], but B will not be a runnable program.
[warn] Reason: companion contains its own main method, which means no static forwarder can be generated.
[warn] object B extends B
- 你知道这个警告的含义吗?
- 为什么 sbt 保证
object B
不会运行,不会发生?
谢谢。
Given the following class and its companion object:
class B extends A
object B extends B
Where A is an abstract class in another file:
abstract class A {
def main(args: Array[String]): Unit = println("hey")
}
The above code is packaged into an uber-jar using the sbt assembly plugin, where the entry point is object B
main method inherited from class B
.
The above works fine. It runs. No problem at all.
Hoewver, sbt keeps warning:
[warn] B has the main method with parameter type Array[String], but B will not be a runnable program.
[warn] Reason: companion contains its own main method, which means no static forwarder can be generated.
[warn] object B extends B
- Do you know the meaning of this warning?
- And why sbt assurance that
object B
won't run, doesn't happen?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于要在 java 中运行的类,
main
需要是静态的。你的不是,所以,该对象不可运行。这就是编译器告诉你的。只需将
A
中的main
重命名为其他名称,然后在调用它的对象中添加一个main
即可。For a class to be runnable in java,
main
needs to be static. Yours isn't, so, the object isn't runnable. That's what compiler is telling you.Just rename
main
inA
to something else, and then add amain
in the object, that calls it.它不适合我。
我有这个文件
B.scala
。当我尝试运行 foo.bar.B 时,出现错误:
原因正如警告所述。 Class
B
包含一个从类A
继承的非静态 main 方法。在一个类中不能有两个名称和类型签名完全相同的方法,即使一个是静态的,另一个是非静态的。这意味着编译器无法在 classB
中生成转发到 objectB 中的非静态 main 方法的静态 main 方法
。我不知道为什么它能为你正确运行。
避免这个问题并不难。只是不要使用伴随对象作为入口点。即重命名类
B
或对象B
。It does not run for me.
I have this file
B.scala
.When I try to run
foo.bar.B
I get an error:And the reason is exactly as the warning says. Class
B
contains a non-static main method which it inherited from classA
. You can't have 2 methods with exactly the same name and type signature in one class, even if one is static and another in non-static. This means that the compiler cannot generate a static main method in classB
that forwards to the non-static main method in objectB
.Why it does run correctly for you I don't know.
It's not so hard to avoid this problem. Just don't use the companion object as an entrypoint. I.e. rename either class
B
or objectB
.