How to compile and run kotlin program in command line with external java library

馋奶兔 提交于 2021-02-07 14:48:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!