Reputation: 431
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.
Upvotes: 1
Views: 110
Reputation: 2319
How about using Class.newInstance() method? I coded a simple example for you:
public <T extends Set> void myMethod(Class<T> type) {
T object;
try {
object = type.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public void caller() {
myMethod(HashSet.class);
}
Is this what you are looking for?
Upvotes: 2
Reputation: 268
If you can use Java8, you can solve this problem easily. Declare the method as follows:
private static List<Set<String>> loadFiles(File[] files, Supplier<Set> setSupplier, Charset charSet)
Change your problem line to:
Set<String> set = setSupplier.get();
Then, in each call to this method, the setSupplier param can be easily provided using method references: HashSet::new, TreeSet::new...
Upvotes: 2
Reputation: 310993
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.
Upvotes: 1