gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:57:54 24 4
gpt4 key购买 nike

我发现我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com