Specifying a generic type in java from Class object

后端 未结 7 1522
野的像风
野的像风 2020-12-11 16:19

Why this is wrong:

    Class type = Integer.class;
    ArrayList = new ArrayList<>();

?

I

7条回答
  •  [愿得一人]
    2020-12-11 16:37

    Feel the difference between java Class (which actually generic too) object and class name.

    You should use class name specifying generic type.

    ArrayList = new ArrayList<>();
    // ArrayList = new ArrayList<>(); <- WRONG
    

    UPD:

    Use this approach if you'll know type only in runtime:

    public  void createAList(Class type) {
        ArrayList toReturn = new ArrayList<>();
        return toReturn;
    }
    

提交回复
热议问题