How are Anonymous inner classes used in Java?

后端 未结 18 1335
孤独总比滥情好
孤独总比滥情好 2020-11-21 05:19

What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?

18条回答
  •  灰色年华
    2020-11-21 05:44

    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.

    Usage

    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!).

    Drawbacks/Limitations

    1. You should pass generic parameter explicitly. Failing to do so will lead to type parameter loss
    2. Each instantiation will cost you additional class to be generated by compiler which leads to classpath pollution/jar bloating

提交回复
热议问题