简体   繁体   English

动态转换对通用类的响应

[英]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 在上面的示例中, ErrorJsonResponse<OtherException>ErrorJsonResponse<RuntimeException>是不可转换的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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