匿名子类在java中是什么意思?

lia*_*ing 0 java json

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

Type type = new TypeToken<Collection<Data>>(){}.getType();
Run Code Online (Sandbox Code Playgroud)

我不明白什么是{}真正的意思。所以我阅读了源代码,并得到了类描述,如:构造一个新的类型文字。从类型参数派生代表类...客户端创建一个空的anonymous subclass. anonymous subclass真的让我困惑吗?谁能具体解释一下?

sma*_*c89 6

{}是一个匿名类的主体。

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

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

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

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
Run Code Online (Sandbox Code Playgroud)

我更喜欢使用这个:

TypeToken<Collection<Data>> tt = new TypeToken<Collection<Data>>(){ };
Type type = tt.getType();
Run Code Online (Sandbox Code Playgroud)

我还想提到的另一件事是匿名类与从同一父级继承的其他匿名类不具有相同的类类型。

所以如果你有以下几点:

TypeToken<Collection<Data>> tt1 = new TypeToken<Collection<Data>>(){ };
TypeToken<Collection<Data>> tt2 = new TypeToken<Collection<Data>>(){ };
Run Code Online (Sandbox Code Playgroud)

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