Class clazz = new Object(){}.getClass();
Why is this possible and what would it mean? Could someone please remind me?
For example:
public class Testing {
public static void main(String[] args) {
Class clazz = new Object(){}.getClass();
System.out.println(clazz);
}
}
The result is: class Testing$1
It creates an anonymous inner class subclassing
Object. The main use I’ve seen with an empty body is in Guice, forTypeLiteral, where it’s used to capture generic type arguments:This is useful because type erasure doesn’t apply to the superclass here, so Guice is able to get the
List<String>part out, which can’t be expressed as a normal class literal.