英文:
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 <E extends Enum<E>> 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 <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.getDeclaringClass())
return enumUsingGson ?: fallbackEnum
}
And getDeclaringClass()
is not recognized in kotlin. I tried using fallbackEnum::class.java
but then I get this error:
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<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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论