如何使用外部Java库在命令行中编译和运行Kotlin程序 [英] How to compile and run kotlin program in command line with external java library
本文介绍了如何使用外部Java库在命令行中编译和运行Kotlin程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是第一次尝试科特林.
I am trying kotlin for the first time.
我能够在命令行上在kotlin中运行编译hello world程序,但无法在要包含外部Java库的地方编译程序
I was able to run compile the hello world program in kotlin on command line but I am not able to compile program where I want to include external java library
import com.google.gson.Gson
data class Person(val name: String, val age: Int, val gender: String?)
fun main(args: Array<String>) {
println("Hello world");
val gson = Gson()
val person = Person("navin", 30, null)
val personJson = gson.toJson(person)
println(personJson)
}
目录结构
➜ kotlin tree
.
├── gson.jar
├── json.jar
└── json.kt
0 directories, 3 files
➜ kotlin
代码编译工作正常,但我无法运行程序
Code compilation works fine but I am not able to run the program
➜ kotlin kotlinc -classpath gson.jar json.kt -include-runtime -d json.jar
➜ kotlin java -jar json.jar -cp gson.jar
Hello world
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/Gson
at JsonKt.main(json.kt:7)
Caused by: java.lang.ClassNotFoundException: com.google.gson.Gson
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
➜ kotlin
需要帮助来了解如何运行上述程序.
Need help understanding how to run the above program.
推荐答案
使用-jar
时,将忽略-cp
参数,因此您无法指定任何其他依赖项.相反,您需要在-cp
参数中指定两个jar:
When you use -jar
, the -cp
argument is ignored, so you can't specify any additional dependencies. Instead, you need to specify both jars in the -cp
argument:
java -cp json.jar:gson.jar JsonKt
这篇关于如何使用外部Java库在命令行中编译和运行Kotlin程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文