java - 创建类型为 "Class"的参数化类型

标签 java generics gson

我发现我的 GSON 问题都与这样一个事实有关:虽然我的返回类型不是参数化对象,但它应该是。现在我需要使用 Gson.fromJson 方法和参数类型来指定返回类型,以便 GSON 帮我处理。

我创建了一个名为 RestResponse 的通用类,如下所示:

public class RestResponse<T> {
  private   String      errorMessage;
  private   int         errorReason;
  private   T           result;

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return "RestResponse [errorMessage=" + errorMessage + ", result=" + result + "]";
  }

  /**
   * Does this response contain an error?
   * @return true if in error
   */
  public boolean isInError(){
    return getErrorMessage()!=null;
  }

  /**
   * @return the errorMessage
   */
  public String getErrorMessage() {
    return errorMessage;
  }

  /**
   * @param errorMessage the errorMessage to set
   */
  public void setErrorMessage(String errorMessage) {
    this.errorMessage = errorMessage;
  }

  /**
   * The error reason code
   * @return the errorReason
   */
  public int getErrorReason() {
    return errorReason;
  }

  /**
   * The error reason code
   * @param errorReason the errorReason to set
   */
  public void setErrorReason(int errorReason) {
    this.errorReason = errorReason;
  }

  /**
   * The result of the method call
   * @return the result or null if nothing was returned
   */
  public final T getResult() {
    return result;
  }

  /**
   * The result of the method call
   * @param result the result to set or null if nothing was returned
   */
  public final void setResult(T result) {
    this.result = result;
  }
}

现在我想在另一侧创建结果类型。我有一个通用方法,用于解码这些内容并抛出异常或返回结果。

所以我的方法是这样的:

public Object submitUrl(String url, Class<?> clazz) throws AjApiException {

其中 clazz 是将在 RestResponse 上指定的类型。

然后,我在传递给 GSON 之前创建 RestResponse:

Type typeOfT = new TypeToken<RestResponse<clazz>>(){}.getType(); //1-->What goes here?
RestResponse<clazz> restResponse; //2-->and here?

而且它出错了。有人能告诉我这些地方用什么来代替 clazz 吗?

最佳答案

不要传入要在响应中包装的类,而是将其指定为方法级别通用参数。

public <T> T submitUrl(String url) throws AjApiException {
    Type typeOfT = new TypeToken<RestResponse<T>>(){}.getType();
}

关于java - 创建类型为 "Class"的参数化类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13801451/

相关文章:

java - Python 代码转换为 JVM

java - 解析 JSON - 无法从 JsonObject 获取 boolean 值

java - java中对象的列表变量的计数

c# - 运算符 '?' 不能应用于类型 'T' 的操作数

c# - 泛型方法中的条件类型

java - 动态类型检查匹配类型参数

android - 使用retrofit2.0解析JSON对象

json - 如何配置 Gson 以序列化一组 JSR-303 ConstraintViolation 对象?

java - 使用java代码代替mapstruct表达式

java - 将接口(interface)方法委托(delegate)给各种类