Is it possible to add Android Java sources to a KM...
# multiplatform
d
Is it possible to add Android Java sources to a KMP project? If so, how? I'm sure this is a stupid question, but I've been unable to find a definitive answer in the usual places. The multiplatform documentation talks about how to add Java sources to the Jvm target here: https://kotlinlang.org/docs/multiplatform-configure-compilations.html#use-java-sources-in-jvm-compilations but this isn't interesting because I don't have a Jvm target, I have an Android target. Any ideas?
m
I would expect it to work the same way. Just create a
java
folder in the
androidMain
directory.
d
That isn't enough. The
java
folder isn't recognized as part of the source tree. The files don't get compiled. Also, just putting java source files in the
kotlin
folder in the source tree doesn't work either. They don't get compiled. I have a feeling that the Java compiler is only applied to the Jvm parts of the source tree, but I don't know why or how to change that behaviour.
m
I have this in my convention plugin.
Copy code
private fun Project.configureMultiplatformAndroidSources() {
        (this.extensions.findByName("android") as? BaseExtension)!!.run {
            sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
            sourceSets["main"].res.srcDir("src/androidMain/res")
            sourceSets["test"].java.srcDir("src/jvmTestCommon/java")
            sourceSets["test"].java.srcDir("src/androidUnitTest/java")
        }
    }
sourceSets["test"].java.srcDir("src/androidUnitTest/java")
part let me do the
java
folder in the
androidUnitTest
so I thought it was just working. So you need to just add
src/AndroidMain/java
to Android's main java source directories. In a gradle.build.kts file it would be
Copy code
android {
    sourceSets["main"].java.srcDir("src/androidMain/java")
}
d
Now Android Studio recognizes that folder as part of the source tree, and it compiles, but when I run a unit test I get a ClassDefNotFoundException on the Java class.
m
that's strange. If it compiles, I would expect it to find the class at runtime. Could be a bug in multiplatform android plugin where the runtime class path isn't including the output directory for java class. I know the tests find the java classes that I create in the test source set. I haven't played with adding java to the main source set.