Create instance of generic type in Java?

后端 未结 27 3092
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 06:14

Is it possible to create an instance of a generic type in Java? I\'m thinking based on what I\'ve seen that the answer is no (due to type erasure), but

27条回答
  •  感情败类
    2020-11-21 06:46

    An imporovement of @Noah's answer.

    Reason for Change

    a] Is safer if more then 1 generic type is used in case you changed the order.

    b] A class generic type signature changes from time to time so that you will not be surprised by unexplained exceptions in the runtime.

    Robust Code

    public abstract class Clazz

    { protected M model; protected void createModel() { Type[] typeArguments = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments(); for (Type type : typeArguments) { if ((type instanceof Class) && (Model.class.isAssignableFrom((Class) type))) { try { model = ((Class) type).newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } } }

    Or use the one liner

    One Line Code

    model = ((Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]).newInstance();
    

提交回复
热议问题