简体   繁体   中英

Dynamically cast response to generic class

I have the following generic class:

public class ErrorJsonResponse<T> {

    private String error;
    private String errCode;
    private String message;
    private T data;

    public ErrorJsonResponse() {
    }

    public ErrorJsonResponse(String error, T data) {
        setError(error);
        setData(data);
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

I need to cast to this class dynamically during run time, like:

(ErrorJsonResponse <runtimeType>) result

How can I do it?

You can cast generic generic classes like this:

public void onResult(ErrorJsonResponse<?> response) {
    ErrorJsonResponse<RuntimeException> castedResponse = (ErrorJsonResponse<RuntimeException>) response;
}

You cannot cast them like this:

public void onResult(ErrorJsonResponse<OtherException> response) {
    ErrorJsonResponse<RuntimeException> castedResponse = (ErrorJsonResponse<RuntimeException>) response;
}

In the above example ErrorJsonResponse<OtherException> and ErrorJsonResponse<RuntimeException> are inconvertible types

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