问题
I want to include jar of Java to Kotlin. I tried like below, but I had error.
javac -encoding utf-8 javasorce/test/JavaTestClass.java
jar cvf javasorce/test/JavaTestClass.jar javasorce/test/JavaTestClass.class
kotlinc kotlin/CallJavaTestClass.kt -cp javasorce/test/JavaTestClass.jar -include-runtime -d kotlin/CallJavaTestClass.jar
java -jar kotlin/CallJavaTestClass.jar
The error is:
Exception in thread "main" java.lang.NoClassDefFoundError:
javasorce/test/JavaTestClass at CallJavaTestClassKt.main(CallJavaTestClass.kt:5)
Caused by: java.lang.ClassNotFoundException: javasorce.test.JavaTestClass
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
I am using like below directories:
root
|-javasorce
| |-test
| |-JavaTestClass.java
|-kotlin
|-CallJavaTestClass.kt
Please tell me if there is solution.
回答1:
In addition to compiling the source code with the Java library on the classpath, you need to run the program with the same library on the classpath: if a class is there at compile time, you need it on the classpath at run time as well to be able to use it.
The correct way of running an application which has its classes scattered across several JARs is to pass those JARs as the classpath to java
and to additionally specify the class that has the main
function:
java CallJavaTestClassKt -cp kotlin/CallJavaTestClass.jar:javasorce/test/JavaTestClass.jar
The command above assumes that you placed the main
function on top level of CallJavaTestClass.kt
(in this case, the class name is formed by the file name with .kt
replaced by Kt
), and it has no package ...
declaration. If you have a package, prepend it to the class name as com.example.FileNameKt
. If you declare main
in an object or a companion object, use the class name or the object name (without Kt
) instead of CallJavaTestClassKt
.
See also: How to run Kotlin class from the command line?
来源:https://stackoverflow.com/questions/46856709/how-to-compile-kotlin-to-include-jar-of-java-with-command-line