Java等价于Kotlin密封类类型检测



我想在Java中访问这个Kotlin类的信息。它通过Gradle库导入。

密封类:

public sealed class Resource<in T> private constructor() {
public final data class Error public constructor(exception: kotlin.Throwable, statusCode: kotlin.Int?) : #.response.Resource<kotlin.Any> {
public final val exception: kotlin.Throwable /* compiled code */
public final val statusCode: kotlin.Int? /* compiled code */
public final operator fun component1(): kotlin.Throwable { /* compiled code */ }
public final operator fun component2(): kotlin.Int? { /* compiled code */ }
}
public final data class Success<T> public constructor(data: T) : com.tsfrm.commonlogic.response.Resource<T> {
public final val data: T /* compiled code */
public final operator fun component1(): T { /* compiled code */ }
}
}

在Java中,我试图确定它的类型是成功还是错误,如果可能的话,我希望能够检索"statusCode"从它。我知道在Kotlin中最好使用'when'逻辑,但我还没能找到合适的替代品。

在Java中你能做的最好的是

public <T> void doResourceThing(Resource<T> r) {
if (r instanceof Success) {
Success<T> success = (Success<T>) r;
...
} else if (r instanceof Error) {
Error err = (Error) r;
...
}
}

最新更新