为什么在Gson中的TypeToken构造是如此奇怪? [英] why the TypeToken construction in Gson is so weird?

查看:893
本文介绍了为什么在Gson中的TypeToken构造是如此奇怪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用Gson在对象和json之间解析时,TypeToken的初始化是如此奇怪:

  new TypeToken< Collection< Integer>>(){}。getType(); 

我只知道这种格式: new TypeToken< Collection< Integer> >()。getType(); ,上面的大括号是什么?提前感谢!



PS 我查看了 TypeToken的源代码类,它是一个(不是接口或抽象),没有任何构造函数,这意味着它使用无参构造函数作为默认值。



PS2 当我删除大括号时,它告诉我构造函数不可见。当我查看TypeToken类时,这是构造函数:

  protected TypeToken(){
this.type = getSuperclassTypeParameter(getClass());
this.rawType =(Class< ;? super T>)$ Gson $ Types.getRawType(type);
this.hashCode = type.hashCode();
}

为什么不使用 public 而不是?

解决方案

Weird不是一个技术术语。该类的定义方式要求您明确指定要与其具体实例相关联的通用参数。因为编译的Java类保存了关于它们的通用参数的信息,所以这些信息对于需要它的框架库是可用的。



这是超类型令牌的目的。 >

When I use Gson to parse between object and json, the initialization of a TypeToken is so weird:

Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();

I just know this kind of format: new TypeToken<Collection<Integer>>().getType();, what's the braces in above for? Thanks in advance!

P.S. I've looked into the source code of TypeToken class, it is a class(not interface or abstract) and without any constructor, which means it uses no-parameter constructor as default.

P.S.2 When I delete the braces, it tell me that the constructor is not visible. When I looked inside the TypeToken class, this is the constructor:

  protected TypeToken() {
        this.type = getSuperclassTypeParameter(getClass());
        this.rawType = (Class<? super T>) $Gson$Types.getRawType(type);
        this.hashCode = type.hashCode();
  }

Why doesn't it just use public instead?

解决方案

'Weird' is not exactly a technical term. The class is defined in such a way as to force you to explicitly specify a generic parameter to be associated with a concrete instance of it. Because compiled Java classes retain information about their generic parameters that information then becomes available to framework libraries that require it.

That's the very purpose of a super type token.

这篇关于为什么在Gson中的TypeToken构造是如此奇怪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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