如何在Kotlin中使用getDeclaringClass?

huangapple go评论54阅读模式
英文:

How to use getDeclaringClass in Kotlin?

问题

I have this method:

protected fun <E : Enum<E>> getEnum(jsonObject: JSONObject, propertyName: String?, fallbackEnum: E): E {
    val fallbackString = toJson(fallbackEnum)
    val jsonString = getString(jsonObject, propertyName, fallbackString)
    val enumUsingGson: E = getEnumUsingGson(jsonString, fallbackEnum::class.java)
    return enumUsingGson ?: fallbackEnum
}

getDeclaringClass() has been replaced with fallbackEnum::class.java in Kotlin. The error you're encountering may be due to other issues in your code, which would require a more in-depth analysis to identify.

英文:

I have this method:

    protected &lt;E extends Enum&lt;E&gt;&gt; E getEnum(JSONObject jsonObject, String propertyName, E fallbackEnum)
{
    String fallbackString = GsonXelion.toJson(fallbackEnum);
    String jsonString = getString(jsonObject, propertyName, fallbackString);
    E enumUsingGson = getEnumUsingGson(jsonString, fallbackEnum.getDeclaringClass());
    return enumUsingGson != null ? enumUsingGson : fallbackEnum;
}

I tried to convert into kotlin and got this:

  protected fun &lt;E : Enum&lt;E&gt;?&gt; getEnum(jsonObject: JSONObject, propertyName: String?, fallbackEnum: E): E {
    val fallbackString = toJson(fallbackEnum)
    val jsonString = getString(jsonObject, propertyName, fallbackString)
    val enumUsingGson: E = getEnumUsingGson(jsonString, fallbackEnum.getDeclaringClass())
    return enumUsingGson ?: fallbackEnum
}

And getDeclaringClass() is not recognized in kotlin. I tried using fallbackEnum::class.java but then I get this error:

如何在Kotlin中使用getDeclaringClass?

What am I doing wrong?

答案1

得分: 1

The code from Java is following:

getEnumUsingJson(String, Class<declaring class of E>;

but, in Kotlin, what you do is:

getEnumUsingJson(String, Class<E>)

So your implementation for Kotlin is different from the original one in Java (deducted type is not compatible with any of possible signatures).

So, what you can do about it? Just pass declaring class of E (instead of just E):

getEnumUsingJson(jsonString, fallbackEnum::class.java.declaringClass)
英文:

The code from Java is following:

getEnumUsingJson(String, Class&lt;declaring class of E&gt;

but, in Kotlin, what you do is:

getEnumUsingJson(String, Class&lt;E&gt;)

So your implementation for Kotlin is different from the original one in Java (deducted type is not compatible with any of possible signatures).

So, what you can do about it? Just pass declaring class of E (instead of just E):

getEnumUsingJson(jsonString, fallbackEnum::class.java.declaringClass)

huangapple
  • 本文由 发表于 2020年1月3日 21:14:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定