Hangman4358 Hangman4358 - 1 month ago 5x
Java Question

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){



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.


If you assume the class has a no-argument accessible constructor, you're basically a newInstance() call away:

Set<String> set = (Set<String) whatType.newInstance();

Note that if you define whatType as a Class<? extends Set> instead of just a raw Class, you can get rid of this ugly cast too.