What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?
Seems nobody mentioned here but you can also use anonymous class to hold generic type argument (which normally lost due to type erasure):
public abstract class TypeHolder {
private final Type type;
public TypeReference() {
// you may do do additional sanity checks here
final Type superClass = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
public final Type getType() {
return this.type;
}
}
If you'll instantiate this class in anonymous way
TypeHolder, Map> holder =
new TypeHolder, Map>() {};
then such holder
instance will contain non-erasured definition of passed type.
This is very handy for building validators/deserializators. Also you can instantiate generic type with reflection (so if you ever wanted to do new T()
in parametrized type - you are welcome!).