16

Gson を使用してオブジェクトと json を解析すると、TypeToken の初期化が非常に奇妙になります。

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

私はこの種の形式を知っています: new TypeToken<Collection<Integer>>().getType();、上記の中括弧は何ですか? 前もって感謝します!

PSTypeTokenクラスのソースコードを調べました。これはclass(インターフェイスでも抽象でもなく)コンストラクターがないため、no-parameter constructorデフォルトとして使用されます。

PS2中かっこを削除すると、コンストラクターが表示されないことがわかります。TypeToken クラスの中を見ると、これがコンストラクターです。

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

public代わりに使用しないのはなぜですか?

4

3 に答える 3

19

「奇妙な」というのは厳密には専門用語ではありません。クラスは、具体的なインスタンスに関連付けられるジェネリック パラメーターを明示的に指定する必要があるように定義されています。コンパイルされた Java クラスは、その汎用パラメーターに関する情報を保持するため、その情報を必要とするフレームワーク ライブラリで利用できるようになります。

それがまさにスーパー タイプ トークンの目的です。

于 2013-03-18T14:55:28.767 に答える
7

new TypeToken<Collection<Integer>>(){} means you are creating an anonymous inner class that extends TypeToken<Collection<Integer>>. Also at the same time you are creating an instance of that anonymous class.

From the link:

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

于 2013-03-18T14:53:17.887 に答える
3

TypeTokenは抽象的であるため、具体的なクラスを作成してインスタンス化する必要があり{}ます。

このコードは具体的な匿名サブクラスを作成し、それをインスタンス化してからインスタンスを呼び出しgetTypeます。

于 2013-03-18T14:51:08.630 に答える