如何使用Maven编译Java + Kotlin项目?
我试图编译有Kotlin类引用Java类的Maven项目。 这是我父母POM的一部分:
... org.jetbrains.kotlin kotlin-stdlib ${kotlin.version} ... org.apache.maven.plugins maven-compiler-plugin ${compiler-plugin-version} ${java-version} ${java-version} ${project.build.sourceEncoding} kotlin-maven-plugin org.jetbrains.kotlin ${kotlin.plugin.version} compile process-sources compile test-compile process-test-sources test-compile false
和POM的相关部分:
org.jetbrains.kotlin kotlin-stdlib ... kotlin-maven-plugin org.jetbrains.kotlin ${project.basedir}/src/main/kotlin
和Kotlin课堂:
Stateless open class DummyServiceImpl : DummyService { PersistenceContext(unitName = Consts.UNIT_NAME) private val em: EntityManager? = null override fun get(id: Long?): Dummy { return em!!.find(javaClass(), id) } override fun sayHi(): String { return "Dummy service says \"Hi!\"." } }
DummyService
和Consts
类是与DummyServiceImpl
驻留在相同模块中的Java类。 所以当我用Maven编译包含DummyServiceImpl
的模块时,它是这样的:
[error] C:\somepath\service\DummyServiceImpl.kt: (14, 31) Unresolved reference: DummyService [error] C:\somepath\service\DummyServiceImpl.kt: (16, 35) Unresolved reference: Consts
如果我切换Kotlin插件执行phase
进行compile
那么如果有从Java到Kotlin类的引用,则可预测性会失败:
[ERROR] /C:/somepath/service/impl/DummyServiceClientImpl.java:[5,27] cannot find symbol [ERROR] symbol: class DummyServiceImpl
那么,这个怎么办? 请注意,使用IDEA制作的make
会非常好。
确保你在你的pom.xml的
中有这个声明
org.jetbrains.kotlin kotlin-maven-plugin ${kotlin.version} compile process-sources compile src/main/java src/main/kotlin src/main/resources test-compile process-test-sources test-compile src/test/java src/test/kotlin src/test/resources
确保配置中提到的所有文件夹 (在src / test中是src / main和3x中的3x) 实际上都存在,即使它们不包含任何类/资源。 一旦它适用于您,您仍然可以微调配置。
还要注意使用与上面提到的完全相同的顺序,让编译器先编译Java代码。
我结束了使用以下配置来混合Java和Kotlin源代码:
${project.basedir}/src/main/java ${project.basedir}/src/test/java org.jetbrains.kotlin kotlin-maven-plugin ${kotlin.version} compile compile compile src/main/kotlin test-compile test-compile test-compile src/test/kotlin
从这个Kotlin + java演示应用程序
您必须执行mvn kotlin:compile
在mvn package
之前mvn kotlin:compile
。 mvn kotlin:compile
会将Kotlin文件编译为类文件。
4.0.0 com.wffweb kotlinminimalproductionsample 0.0.1 war yyyyMMddHHmmss UTF-8 UTF-8 1.8 1.8 1.2.21 javax.servlet javax.servlet-api 3.1.0 provided javax.websocket javax.websocket-api 1.1 provided com.webfirmframework wffweb RELEASE org.jetbrains.kotlin kotlin-stdlib-jdk8 ${kotlin.version} org.jetbrains.kotlin kotlin-test ${kotlin.version} test src/main/java **/*.properties org.codehaus.mojo exec-maven-plugin 1.4.0 org.apache.maven.plugins maven-compiler-plugin 3.3 1.8 1.8 org.jetbrains.kotlin kotlin-maven-plugin ${kotlin.version} compile compile compile test-compile test-compile test-compile 1.8