android-studioandroid-jetpack-composeandroid-jetpack-compose-preview

Jetpack Compose preview ClassNotFoundException when class is defined in java module


My app has a module that uses Jetpack Compose and another non-Android (plain Java Library) module with some Java classes. I ran into an issue where Jetpack Compose preview is failing with a render error if I use a class defined in a plain Java/Kotlin module, and throws:

java.lang.ClassNotFoundException: <ClassName>   at java.lang.ClassLoader.loadClass  at java.lang.ClassLoader.loadClass ...

Java module is added to dependencies of Compose module:

implementation project(':java-common')

Everything compiles and runs on the device just fine. The problem occurs only in the preview. If I define the same class in Android library module, then the preview works as well, so I think the issue is that the class is defined in Java/Kotlin module. Here is the build file for the library module:

plugins {
    id("java-library")
    id("org.jetbrains.kotlin.jvm")
}

kotlin {
    jvmToolchain(17)
}

java {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
}

Am I missing some configuration in the library module? (I really don't want to turn it into Android module, because there are some other non-Android parts of the project that use it).

I am using AS Flamingo with AGP 8.0.2 and Kotlin 1.8.22.


Solution

  • In the end, after spending an entire day scratching my head, the problem was solved by re-importing the project (full clean, delete .idea folder).