6

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.

2
  • Try putting the -jar json.jar last when running your jar file Commented Dec 2, 2018 at 16:41
  • Didn't work, got same error. Commented Dec 3, 2018 at 8:40

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

to run from command line, Kotlin program which is using external library for compile :

kotlinc -cp "C:\Users\<user>\Desktop\kotlin\programs\gson-2.10.jar" GsonTest.kt

for run:

kotlin -cp ".;C:\Users\<user>\Desktop\kotlin\programs\gson-2.10.jar" GsonTestKt

note: please give full path location for external jar's as mention above, user will be your system name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.