How to compile Kotlin to include jar of Java with command line?

回眸只為那壹抹淺笑 提交于 2021-02-10 05:44:05

问题


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

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