Gson非法类型变量引用 [英] Gson illegal type variable reference

查看:954
本文介绍了Gson非法类型变量引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类定义为:

public class Calls<T extends Object>

在这个类中有一个方法 doRequest 为Gson请求创建 TypeToken (来自 com.google.json.reflect )。

Inside this class there is a method doRequest that creates a TypeToken (from com.google.json.reflect) for a Gson request.

java.lang.reflect.Type type = new TypeToken<HandlerResponse<T>>(){{}}.getType();

其中 HandlerResponse 是一个简单的模型类,包含如下属性:

where HandlerResponse is a simple model class that contains attributes like:

private Map detail;

private transient T data;

private transient int count = 0;

private String status;

我在Android Studio上遇到的异常是:

The exception I get on Android Studio is:

FATAL EXCEPTION: main
Process: PID: 32628
java.lang.AssertionError: illegal type variable reference
    at libcore.reflect.TypeVariableImpl.resolve(TypeVariableImpl.java:111)
    at libcore.reflect.TypeVariableImpl.getGenericDeclaration(TypeVariableImpl.java:125)
    at libcore.reflect.TypeVariableImpl.hashCode(TypeVariableImpl.java:47)
    at java.util.Arrays.hashCode(Arrays.java:4153)
    at com.google.gson.internal.$Gson$Types$ParameterizedTypeImpl.hashCode($Gson$Types.java:479)
    at com.google.gson.reflect.TypeToken.<init>(TypeToken.java:64)
    at com.company.server.Calls$4.<init>(Calls.java:244)

在TypeToken的实例化时崩溃了(我想这可能是因为类型擦除而丢失了T类的原因

crashes at the instantiation of the TypeToken (I was thinking that probably is losing the T class 'cause of the type erasure of Java).

创建实例

I create the instance of Calls as:

Calls<com.company.model.beans.Model> calls = new Calls<>(){};


推荐答案

解决方案我修改了如下实现: p>

Solved, I modified the implementation as follows:

public class Calls<T> {

    public Calls(Type type, Class classTypeResponse) {

        this.type = type;
        this.classTypeResponse = classTypeResponse;
    }

    doRequest(...) { ... }

    ...
}

我有一个 classTypeResponse ,因为我有一个回调系统,它为对象请求。

I have a classTypeResponse because I have a callback system that returns the right class type for the object for the request.

我这样调用它:

I call it in this way:

Type type = new TypeToken<HandlerResponse<com.company.model.beans.Model>>(){}.getType();

Calls<com.company.model.beans.Model> calls = new Calls<>(type, com.company.model.beans.Model.class);

calls.doRequest(...);

T 在运行时不存在,Java反射系统无法推断 TypeToken 的正确类型。解决方案是在没有泛型的情况下创建 TypeToken ,并在需要的地方传递对象。

The T doesn't exists at runtime, Java reflection system couldn't infer the right type for the TypeToken. The solution is to create the TypeToken without generics and pass the object where you need it.

这篇关于Gson非法类型变量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆