23

I was looking into the Guava library and I came across an empty anonymous inner class in TypeToken.

TypeToken<List<String>> stringListTok = new TypeToken<List<String>>() {};

What is exactly use of empty anonymous inner class and what are the useful scenarios where it can be helpful?

Priyank Doshi
  • 12,895
  • 18
  • 59
  • 82

2 Answers2

34

The purpose of this is to allow TypeToken to find the superclass of the instance - which will preserve the type argument information.

For example, although an ArrayList<String> object doesn't know that that its element type is String, due to erasure, the superclass information is not lost, so new ArrayList<String>{} knows that its superclass is ArrayList<String>, not just ArrayList. TypeToken uses that technique to represent a constructed generic type.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 3
    I've been using `TypeToken` for some time, but never quite appreciated the subtlety and cleverness. That is pretty awesome – Ray Sep 26 '12 at 18:18
19

There's one use, that Guava might use. As you know, types are lost after compilation, but if the type is spefied at the class level, then it's not lost after compilation and it can be extracted by reflection. I'll put the code to extract the type in a minute.


Edit I don't know if the code is of any use, but here it's

public class Reflect {

    public static void main(String[] args) {
        Super<String> aStringSuper = new Super<String>() {};
        aStringSuper.method();

        Super<List<Integer>> aListSuper = new Super<List<Integer>>() {};
        aListSuper.method();
    }

}

class Super<T> {

    public void method() {
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
        for(Type type : parameterizedType.getActualTypeArguments()) {
            System.out.println(type);
        }
    }
}
Augusto
  • 28,839
  • 5
  • 58
  • 88