从Java调用Kotlin(找不到符号)

vnzz0bqm  于 2023-01-09  发布在  Kotlin
关注(0)|答案(4)|浏览(159)

我正在尝试从Java调用Kotlin中的函数。
文档上说这很容易。到目前为止,我一直没有运气跟随这个帖子。
https://kotlinlang.org/docs/java-to-kotlin-interop.html#package-level-functions
在Java中键入时,IDE可以识别该类,但在编译时显示 *error:找不到符号 *
任何帮助都是非常欢迎的。
app.kt

package org.cocos2dx.cpp

fun getTime() { /*...*/ }

AppActivity.java

public void test1() {
        org.cocos2dx.cpp.AppKt.getTime();
    }

项目结构

/proj.android
   /app
       /src
          /org.cocos2dx.cpp
              app.kt
              AppActivity

项目级别build.gradle

buildscript {
    ext.kotlin_version = "1.5.0"
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.8'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.7.0'
    }
}

allprojects {
    repositories {
        google()
        mavenCentral() 
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

模块级build.gradle

import org.gradle.internal.os.OperatingSystem

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'

android {
    compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger()

    defaultConfig {
        applicationId "demo.1"
        minSdkVersion PROP_MIN_SDK_VERSION
        targetSdkVersion PROP_TARGET_SDK_VERSION
        versionCode 43
        versionName "0.43"

        externalNativeBuild {
            cmake {
                targets 'MyGame'
                arguments "-DCMAKE_FIND_ROOT_PATH=", "-DANDROID_STL=c++_static", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_NEON=TRUE"
                cppFlags "-frtti -fexceptions -fsigned-char"
            }
        }

        ndk {
            abiFilters = []
            abiFilters.addAll(PROP_APP_ABI.split(':').collect{it as String})
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    sourceSets.main {
        java.srcDir "src"
        res.srcDir "res"
        manifest.srcFile "AndroidManifest.xml"
        assets.srcDir "../../Resources"
    }

    externalNativeBuild {
        cmake {
            path "../../CMakeLists.txt"
        }
    }

    signingConfigs {
       release {
            if (project.hasProperty("RELEASE_STORE_FILE")) {
                storeFile file(RELEASE_STORE_FILE)
                storePassword RELEASE_STORE_PASSWORD
                keyAlias RELEASE_KEY_ALIAS
                keyPassword RELEASE_KEY_PASSWORD
            }
        }
    }

    buildTypes {
        release {
            debuggable false
            jniDebuggable false
            renderscriptDebuggable false
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            if (project.hasProperty("RELEASE_STORE_FILE")) {
                signingConfig signingConfigs.release
            }
        }

        debug {
            debuggable true
            jniDebuggable true
            renderscriptDebuggable true
        }
    }
}

android.applicationVariants.all { variant ->
    def project_root_folder = "${projectDir}/../.."
    def dest_assets_folder = "${projectDir}/assets"

    delete dest_assets_folder
    def targetName = variant.name.capitalize()
    def copyTaskName = "copy${targetName}ResourcesToAssets"
    
    tasks.register(copyTaskName) {
        copy {
            from "${buildDir}/../../../Resources"
            into "${buildDir}/intermediates/assets/${variant.dirName}"
            exclude "**/*.gz"
        }
    }
    tasks.getByName("pre${targetName}Build").dependsOn copyTaskName
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(':libcocos2dx')
    implementation 'androidx.core:core:1.0.0'
    implementation platform('com.google.firebase:firebase-bom:28.1.0')
    implementation 'com.google.firebase:firebase-crashlytics-ktx'
    implementation 'com.google.firebase:firebase-analytics-ktx'
}

错误

error: cannot find symbol
        org.cocos2dx.cpp.AppKt.getTime();
                        ^
  symbol:   class AppKt
  location: package org.cocos2dx.cpp
2exbekwf

2exbekwf1#

您的代码看起来很好;但您需要具有项目级build.gradle类路径:
第一个月

buildscript {
    ext.kotlin_version = "1.5.0"
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.0"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

build.gradle模块级别中的Kotlin标准库依赖项:

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 
}
kt06eoxx

kt06eoxx2#

您可以通过将java文件移动到java源目录下,然后将Kotlinkt文件保留在kotlin源目录下来解决此问题。
之后,您的文件结构可能更像这样:

proj.android/
├─ app/
│  ├─ src/
│  │  ├─ kotlin/
│  │  │  ├─ org.cocos2dx.cpp/
│  │  │  │  ├─ app.kt
│  │  ├─ java/
│  │  │  ├─ org.cocos2dx.cpp/
│  │  │  │  ├─ AppActivity

在多项目中(使用JPMS),我还必须添加

compileKotlin.destinationDir = compileJava.destinationDir

到我的大楼,Gradle

relj7zay

relj7zay3#

尝试在Kotlin函数中使用**@JVMStatic**。

@JVMStatic
fun getTime() { /*...*/ }

从JAVA

public void test1() {
   AppKt.getTime();
}

这应该行得通。

y53ybaqx

y53ybaqx4#

确保您的项目和模块级build.gradle文件与以下内容匹配:

plugins {
        id 'com.android.application' version '7.3.1' apply false
        id 'com.android.library' version '7.3.1' apply false
        id 'org.jetbrains.kotlin.android' version '1.7.20' apply false
    }

    plugins {
        id 'com.android.application'
        id 'org.jetbrains.kotlin.android'
        id 'kotlin-kapt'
    }

相关问题