Why {} is used in this expression for an instance, Type collectionType = new TypeToken <Collection <Integer>> () {}. GetType ();

Please explain why it is {}used in

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

This is from the Gson documentation a link to the documentation

+4
source share
1 answer

Creates a new anonymous type. This is a temporary workaround for type erasing because you can get Collection<Integer>with Class.getGenericSuperclass()and Class.getGenericInterfaces()if the class is not generic (*).

This code basically implements the same functions Ideone demo:

abstract class TypeToken<T> {
  Type getType() {
    ParameterizedType t = (ParameterizedType) getClass().getGenericSuperclass();
    return t.getActualTypeArguments()[0];
  }
}

public static void main (String[] args) {
    Collection<Integer> list = new ArrayList<>();
    System.out.println(list.getClass().getGenericInterfaces()[0]);

    TypeToken<Collection<Integer>> tt = new TypeToken<Collection<Integer>>() {};

    System.out.println(tt.getClass().getGenericSuperclass());
    System.out.println(tt.getType());
}

Conclusion:

java.util.List<E>
Ideone.Ideone$TypeToken<java.util.Collection<java.lang.Integer>>
java.util.Collection<java.lang.Integer>

, "" Collection ; TypeToken, getType().


(*) , () TypeToken . :

<T> TypeToken<T> getGenericToken() {
  return new TypeToken<T>() {};
}

, Ideone demo.

TypeToken<Collection<String>> t = getGenericToken();
System.out.println(t.getType()); // T, not Collection<String>.
+3

Source: https://habr.com/ru/post/1690371/


All Articles