简体   繁体   English

Android 从 Kotlin 调用非静态 Java 方法

[英]Android call non-static Java method from Kotlin

I am trying to call a non-static Java method from a Kotlin file as I need to be able to use findViewById.我正在尝试从 Kotlin 文件调用非静态 Java 方法,因为我需要能够使用 findViewById。 However When I changed my method to non-static the Kotlin file returned the following error: Unresolved reference: main.但是,当我将方法更改为非静态时,Kotlin 文件返回以下错误:未解析的引用:main。 When the Java method was static the Kotlin file was able to run the Java method.当 Java 方法为静态时,Kotlin 文件能够运行 Java 方法。

Kotlin File:科特林文件:

class RoundFactoryImpl(private val randomiser: Randomiser) : RoundFactory {
     override fun buildRound(cards: List<Card>): Round = Round()
     val card = Round()
     val customer = PokemonRand.main(randomiser, card)
}

Java File: Java文件:

public void main(Randomiser randomiser, Round cards) {
    Card cardA, cardB;

    cardA = getCard(randomiser, cards);
    cardB = getCard(randomiser, cards);

    Log.d("cardA", cardA.toString());
    Log.d("cardB", cardB.toString());

    while (cardA.getRarity() == cardB.getRarity()) {
        cardB = getCard(randomiser, cards);
    }

    dispCard(cardA, cardB);
    compCard(cardA, cardB);
}
val customer = PokemonRand.main(randomiser, card)

First issue with your code is you are assigning the value of your main method to customer variable whose return type is void ;您的代码的第一个问题是您将main方法的值分配给返回类型为void customer变量;

Second problem with the code is your main method is not static so you need to create an instance of the PokemonRand class and call the main method on that instance like the following代码的第二个问题是您的 main 方法不是静态的,因此您需要创建PokemonRand类的一个实例并调用该实例上的main方法,如下所示

val pokemon = PokemonRand();
pokemon.main(randomiser, card);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM