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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With