mardi 23 août 2016

Creating object from a given Class object in Java

quick question about creating objects when given a Class object. Or maybe I need to go about this differently. First off my plan, I am writing a method that will take an array of File objects, and read each one into a Set, where each set is then appended to a list and the list returned. Below is what I have:

private static List<Set<String>> loadFiles(File[] files, Class whatType, Charset charSet){
    List<Set<String>> setList = new ArrayList<Set<String>>(files.length);

    try {
        for(File f : files){
            BufferedInputStream bs = new BufferedInputStream(new FileInputStream(f));
            InputStreamReader r = new InputStreamReader(bs, charSet);
            BufferedReader br = new BufferedReader(r);

            Set<String> set = new HashSet<>(); //This is the problem line
            String line = null;

            while( (line = br.readLine()) != null){
                set.add(line.trim());

            }

            br.close();
            setList.add(set);
        }

        return setList;
    } catch (FileNotFoundException e) {
        //Just return the empty setlist
        return setList;
    } catch (IOException e) {
        //return a new empty list
        return new ArrayList<Set<String>>();
    }
}

But what I want is to allow the user of the method to specify the type of Set to instantiate (as long as it contains Strings of course). That is what the 'whatType' param is for.

All my research has lead me to how to instantiate an object given the class name, but that is not really what I am after here...

Maybe I need to go about this a different way? Any help is really appreciated!





Aucun commentaire:

Enregistrer un commentaire