问题
I am trying kotlin for the first time.
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)
}
Directory structure
➜ 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.
回答1:
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
来源:https://stackoverflow.com/questions/53582212/how-to-compile-and-run-kotlin-program-in-command-line-with-external-java-library