Pass class type as parameter to use in ArrayList?

前端 未结 4 2017
离开以前
离开以前 2020-12-17 00:28

I need to write a java method which takes a class (not an object) and then creates an ArrayList with that class as the element of each member in the array. Pseudo-code exam

4条回答
  •  青春惊慌失措
    2020-12-17 00:40

    Vlad Bochenin gives a good way but it makes no sense to provide a T generic that derives from nothing in your method.
    It puts zero constraints in the code of insertData() that manipulates the list.
    You will be forced to do cast in the code and it defeats the purpose of Generics.

    I suppose you want manipulate some instances of known classes in insertData().
    And if you use generic in your case, it would have more meaningful if you have subtypes of classes to manipulate.

    In this way, you could have a method that accepts a base type and its subclases.

    public static  void insertData(Class clazz, String fileName) {
        List newList = new ArrayList<>();
        T t = newList.get(0);
        // here I can manipulate something that derives from YourClass
    }
    

提交回复
热议问题