Pass class type as parameter to use in ArrayList?

前端 未结 4 2019
离开以前
离开以前 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 01:01

    You can use Generic methods

    public  void insertData(Class clazz, String fileName) {
       List newList = new ArrayList<>();
    }
    

    but if you should use this contract insertData(String className, String fileName), you cannot use generics because type of list item cannot be resolved in compile-time by Java.

    In this case you can don't use generics at all and use reflection to check type before you put it into list:

    public void insertData(String className, String fileName) {
        List newList = new ArrayList();
    
        Class clazz;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e); // provide proper handling of ClassNotFoundException 
        }
    
        Object a1 = getSomeObjectFromSomewhere();
    
        if (clazz.isInstance(a1)) {
            newList.add(a1);
        }
        // some additional code
    }
    

    but without information of class you're able use just Object because you cannot cast your object to UnknownClass in your code.

提交回复
热议问题