Pass class type as parameter to use in ArrayList?

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

    It is not a good practice, just an example of using Object and

    this.array_employee = loadDataArrayListFromFileJson(fileName_employee, Employee.class);
    this.array_movie = loadDataArrayListFromFileJson(fileName_movie, Movie.class);
    this.array_store = loadDataArrayListFromFileJson(fileName_store, Store.class);
    
    private  ArrayList loadDataArrayListFromFileJson(String filename, Class class__) {
        ArrayList arraylist_objects = new ArrayList<>();
    
        String jsonArrayString = getResourceAsString(filename);
        JsonParser parser = new JsonParser();
        Gson gson = new Gson();
    
        JSONArray json_array = new JSONArray(jsonArrayString);
        for (Object object : json_array) {
            JsonElement json_element = parser.parse(object.toString());
            Object element = gson.fromJson(json_element, class__);
            System.out.println(element);
            arraylist_objects.add((T) element);
        }
        return arraylist_objects;
    }
    

提交回复
热议问题