2016-04-22 83 views
-1

最近,我正在学习使用Google的Gson的JSON。我遇到了一个问题。这里是代码:匿名子类在java中的含义是什么?

Type type = new TypeToken<Collection<Data>>(){}.getType(); 

我不明白什么{}真正mean.So我读的源代码,并获得类的描述,如:构造一个新的类型文本。派生表示类从类型参数...客户端创建一个空的anonymous subclassanonymous subclass真的让我困惑?任何人都可以具体解释一下吗?

+0

你问的是类型令牌或对一般的匿名类? – Savior

+0

下面是类型令牌“黑客”的解释:http://stackoverflow.com/questions/22271779/is-it-possible-to-use-gson-fromjson-to-get-arraylistarrayliststring – Savior

回答

2

{}是匿名类的主体。

为你所拥有的完整定义是这样的:

class MyTypeToken extends TypeToken<Collection<Data>> { 

} 

TypeToken<Collection<Data>> tcd = new MyTypeToken(); 
Type type = tcd.getType(); 

而不必输入所有说出来,Java允许您简化它只是:

Type type = 
    new TypeToken<Collection<Data>>() // this is the constructor 
    { 
     // in here you can override methods and add your own if you want 
    } // this ends the declaration of the class. At this point the class is created and initialized 
    .getType(); // This is method of the class and semicolon to end the expression 

注意,由于类是匿名的,你必须在创建它的同时对它进行初始化。如果尝试后,初始化它,战胜它的匿名

你也可以这样做:

TypeToken<Collection<Data>> tt = new TypeToken<Collection<Data>>(){}; 
Type type = tt.getType(); 
+0

你的答案真的帮助我。谢谢。 – liaoming