简体   繁体   English

如何将任何Kotlin枚举(仅在运行时已知)作为参数传递给Java代码中的方法?

[英]How to pass any (known at runtime only) Kotlin enum as parameter to a method in Java code?

Say we have enums 说我们有枚举

enum class Status {
    OPEN, CLOSED
}

enum class Weekday {
    WORKDAY, DAYOFF
}

Having a Java class 有一个Java类

public KotlinInvoker {
    public methodWithKotlinEnumAsParameter_namely_AppendWorkingStatusString( ? kotlinEnum) {
    ...
    }
}

The Goal is to directely pass ANY jave / kotlin enum to that kind of the function like if Java you would have a 目标是将任何jave / kotlin枚举直接传递给该函数,例如,如果Java,

    <E extends java.lang.Enum<E>>
    methodAcceptingEnumAsParameter(E enum) {
    ...
    return result + ' ' + enum.toString();
    }

so you can pass ANY enum to it. 因此您可以将任何枚举传递给它。 what should be the method signature to play nicely with kotlin enum as well as it is mapped to java enum accordingly to official kotlin docs? 可以与kotlin枚举很好地配合使用的方法签名应该是什么,并且根据官方kotlin文档将其映射到java枚举?

Your Java example works in Kotlin just fine: 您的Java示例可以在Kotlin中正常运行:

enum class Status {
    OPEN, CLOSED
}

enum class Weekday {
    WORKDAY, DAYOFF
}

fun <E : Enum<E>> methodWithKotlinEnumAsParameter(arg : E)
{
    println(arg.name)
}

Now, if you for example call methodWithKotlinEnumAsParameter(Weekday.DAYOFF) , it will print DAYOFF to the console. 现在,例如,如果您调用methodWithKotlinEnumAsParameter(Weekday.DAYOFF) ,它将打印DAYOFF到控制台。

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

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