简体   繁体   中英

Java Equivalent of Kotlin Sealed Class Type Detection

I want to access information from this Kotlin class in Java. It is being imported via a Gradle library.

Sealed Class:

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 */ }
}
}

In Java, I'm trying to determine whether it is of type Success or Error, and if possible, I want to be able to retrieve the "statusCode" from it. I know in Kotlin it'd be preferable to use the 'when' logic in Kotlin, but I haven't been able to find a suitable replacement for it.

The best you can do in Java is

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;
    ...
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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