如何使用 Maven 编译 Java+Kotlin 项目?
我正在尝试编译 maven 项目,其中有引用 Java 类的 Kotlin 类。这是我父母POM的一部分:
...
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin-version}</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.plugin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>process-test-sources</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<scanForAnnotations>false</scanForAnnotations>
</configuration>
</plugin>
以及子POM的相关部分:
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
</dependency>
...
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<configuration>
<sourceDirs>
<source>${project.basedir}/src/main/kotlin</source>
</sourceDirs>
</configuration>
</plugin>
还有 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<Dummy>(javaClass<Dummy>(), id)
}
override fun sayHi(): String {
return "Dummy service says \"Hi!\"."
}
}
DummyService
和类是与 驻留在同一模块中的 Java 类。因此,当我编译包含 Maven 的模块时,它是这样的:Consts
DummyServiceImpl
DummyServiceImpl
[error] C:\somepath\service\DummyServiceImpl.kt: (14, 31) Unresolved reference: DummyService
[error] C:\somepath\service\DummyServiceImpl.kt: (16, 35) Unresolved reference: Consts
如果我将 Kotlin 插件执行切换为,那么如果有从 Java 到 Kotlin 类的引用,它可以预见地失败:phase
compile
[ERROR] /C:/somepath/service/impl/DummyServiceClientImpl.java:[5,27] cannot find symbol
[ERROR] symbol: class DummyServiceImpl
那么,该怎么办呢?请注意,使用IDEA构建完全正常。make