Specifying a generic type in java from Class object

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

Why this is wrong:

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

?

I

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 16:49

    ArrayList = new ArrayList<>();
    

    this line is wrong. First, you missed identifier (variable name) here; Second, you mixed the concepts of "type" and "class". You can delcare

    ArrayList list = new ArrayList<>();
    

    But according to yours, type = Integer.class. Obviously, Integer is not equivalent to Integer.class. Similarly you can't have Integer.class i = 1; The former one is a "type", the second one is a "Class" object.

    You can create a generic method:

    public  List createAList (Class type) {
        return new ArrayList();
    }
    

提交回复
热议问题