Could not find or load main class com.xxx.xxx.XXXKt reason

Error: Could not find or load main class com.xxx.xxx.XXXKt
Cause: java.lang.ClassNotFoundException: com.xxx.xxx.XxxxKt

In the Android project, if you want to make a main function as the entry point of the program, Java's main() is not acceptable, because in the Android program, only Application can be the entry point of the program. So kotlin's fun main(){} is naturally used as the entry point of some test methods. Of course, you can also write the test() function.

If in this case, you run fun main(){ } and cannot find the compiled Kt class, it is likely that you have not introduced the kotlin dependency into this project, resulting in the inability to compile kotlin code in this project .

How to configure kotlin in Android (Java) project? as follows:

plugins {
    id 'com.android.application'

    //ToDo 要在Java项目中添加kotlin依赖才可以使用和编译kt文件,来作为某些程序的入口
    // 避免写Java main()但又不能作为程序入口的尴尬
    id 'org.jetbrains.kotlin.android'
}

android {
    namespace 'com.xxx.xxx'
    compileSdk 33

    defaultConfig {
        applicationId "com.xxx.xxx"
        minSdk 24
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    //ToDo 要在Java项目中添加kotlin依赖才可以使用和编译kt文件,来作为某些程序的入口
    // 避免写Java main()但又不能作为程序入口的尴尬
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    //ToDo 要在Java项目中添加kotlin依赖才可以使用和编译kt文件,来作为某些程序的入口
    // 避免写Java main()但又不能作为程序入口的尴尬
    implementation 'androidx.core:core-ktx:1.7.0'

    implementation 'androidx.appcompat:appcompat:1.6.0'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

Guess you like

Origin blog.csdn.net/Goals1989/article/details/128719262