Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty anonymous inner class in java

Tags:

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?

like image 617
Priyank Doshi Avatar asked Sep 22 '12 10:09

Priyank Doshi


People also ask

What is anonymous inner class in Java?

In Java, a class can contain another class known as nested class. It's possible to create a nested class without giving any name. A nested class that doesn't have any name is known as an anonymous class. An anonymous class must be defined inside another class. Hence, it is also known as an anonymous inner class.

Is an anonymous class an inner class?

Anonymous classes are inner classes with no name. Since they have no name, we can't use them in order to create instances of anonymous classes. As a result, we have to declare and instantiate anonymous classes in a single expression at the point of use. We may either extend an existing class or implement an interface.

Which is true about an anonymous inner class in Java?

D is correct. It defines an anonymous inner class instance, which also means it creates an instance of that new anonymous class at the same time. The anonymous class is an implementer of the Runnable interface, so it must override the run() method of Runnable.

Where can you use an anonymous inner class?

An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class. Tip: Anonymous inner classes are useful in writing implementation classes for listener interfaces in graphics programming.


1 Answers

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.

like image 110
Jon Skeet Avatar answered Sep 17 '22 07:09

Jon Skeet