确保kotlin方法是静态的,顶级的或注释的@JvmStatic
如何将main
声明为static,以便该方法按照以下方式运行(交互式):
thufir@dur:~/kotlin$ thufir@dur:~/kotlin$ kotlinc Welcome to Kotlin version 1.1.51 (JRE 9.0.0.15+181) Type :help for help, :quit for quit >>> >>> println("hello world"); WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by com.intellij.util.text.StringFactory to constructor java.lang.String(char[],boolean) WARNING: Please consider reporting this to the maintainers of com.intellij.util.text.StringFactory WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release hello world >>> >>> :quit thufir@dur:~/kotlin$
编译:
thufir@dur:~/kotlin$ thufir@dur:~/kotlin$ kotlinc Hello.kt WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by com.intellij.util.text.StringFactory to constructor java.lang.String(char[],boolean) WARNING: Please consider reporting this to the maintainers of com.intellij.util.text.StringFactory WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release thufir@dur:~/kotlin$ thufir@dur:~/kotlin$ kotlin HelloKt error: could not find or load main class HelloKt thufir@dur:~/kotlin$ thufir@dur:~/kotlin$ kotlin Hello error: 'main' method of class Hello is not static. Please ensure that 'main' is either a top level Kotlin function, a member function annotated with @JvmStatic, or a static Java method thufir@dur:~/kotlin$ thufir@dur:~/kotlin$ cat Hello.kt class Hello { public fun main(args: Array) { println("Hello, world!" + args[0]) } } thufir@dur:~/kotlin$
也可以看看:
https://kotlinlang.org/docs/tutorials/command-line.html
在教程中,该方法是在顶层声明的,而不是在class Hello
。 或者,你可以写
import kotlin.jvm.JvmStatic object Hello { @JvmStatic public fun main(args: Array) { println("Hello, world!" + args[0]) } }
- Gradle忽略kotlin jvmname?
- 将Kotlin .class文件打包到JAR中执行
- Kotlin:避免创建FqNameUnsafe和FqName
- 将@JvmStatic和@JvmField自动应用于Kotlin中的所有文件
- 如何从字符串转换为Kotlin类的接口/类?
- 简单的方法来找出一个类是匿名/对象,并从Kotlin实例中获取具体的类名
- Kotlin:如何在运行时在OneClass 中获得实际的genericstypesT.
- 在Kotlin中,我如何习惯性地访问可空的嵌套地图值,或者返回一个默认值?
- Kotlin:UnsupportedOperationException用于get / set操作符