如何通过命令行编译Kotlin以包含Java jar? [英] How to compile Kotlin to include jar of Java with command line?

查看:52
本文介绍了如何通过命令行编译Kotlin以包含Java jar?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Java的jar包含在Kotlin中.我尝试如下进行操作,但出现错误.

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

错误是:

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

我正在使用以下目录:

root
|-javasorce
| |-test
|   |-JavaTestClass.java
|-kotlin
  |-CallJavaTestClass.kt

请告诉我是否有解决办法.

Please tell me if there is solution.

推荐答案

除了使用classpath上的Java库编译源代码外,还需要使用classpath上相同的库来运行程序:在编译时,您也需要在运行时在类路径上使用它.

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.

运行其类分散在几个JAR中的应用程序的正确方法是将这些JAR作为类路径传递给 java ,并另外指定具有 main 的类.代码>功能:

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

上面的命令假定您将 main 函数放置在 CallJavaTestClass.kt 的顶层(在这种情况下,类名由文件形成)名称,用 .kt 替换为 Kt ),并且没有 package ... 声明.如果您有一个软件包,则将其作为 com.example.FileNameKt 放在类名之前.如果在对象或伴随对象中声明 main ,请使用类名或对象名(不带 Kt )而不是 CallJavaTestClassKt .

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.

另请参阅: 如何从命令行运行Kotlin类?

See also: How to run Kotlin class from the command line?

这篇关于如何通过命令行编译Kotlin以包含Java jar?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆