【问题标题】:What does anonymous subclass mean in java? [duplicate]java中的匿名子类是什么意思? [复制]
【发布时间】:2016-08-16 10:03:01
【问题描述】:

最近,我正在使用 Google 的 Gson 学习 JSON。我遇到了一个问题。这是代码:

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

我无法理解 {} 的真正含义。所以我阅读了源代码,得到了类描述,例如:构造一个新的类型文字。从类型参数派生表示的类...客户端创建一个空的anonymous subclassanonymous subclass 真的让我很困惑吗?谁能具体解释一下?

【问题讨论】:

标签: java json


【解决方案1】:

{} 是匿名类的主体。

如果你想让它更具可读性,它可能是这样的:

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

以下是您使用的更简洁的速记的细分:

Type type =
    new TypeToken<Collection<Data>>() { // this will initialise an anonymous object
        /* in here you can override methods and add your own if you need to */

    }   /* this ends the initialisation of the object. 
           At this point the anonymous class is created and initialised. */

    .getType(); // here you call a method on the object

我更喜欢使用这个:

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

我还想提一提的是,匿名类的类类型与其他继承自同一个父类的匿名类不同。

如果你有以下情况:

TypeToken<Collection<Data>> tt1 = new TypeToken<Collection<Data>>(){ };
TypeToken<Collection<Data>> tt2 = new TypeToken<Collection<Data>>(){ };

tt1.getClass() == tt2.getClass()永远是真的。

【讨论】:

  • 您的回答对我很有帮助。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
  • 2015-06-08
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
相关资源
最近更新 更多