Reputation: 53
public CountryComponent(String sorter)throws IOException
{
String sort = sorter;
getData();
Collections.sort(countriesList, new sort());
}
basically in my FrameViewer class im providing a menu of options for different sorting methods, im stuck on how to pass along the class name for my different comparators as an argument
the above was my test. but the .sort(ob, comparator) is expecting it to be the name of the comparator class
I was originally just going to manually type in the specific class name as the String passed along
ex: CountryComponent canvas = new CountryComponent(PopSorter);
then I was hoping it would end up being Collections.sort(countriesList, new PopSorter());
I saw some things about instanceOf, but I really didnt understand it, I wasnt too sure what they were trying to do was exactly what I was trying to do
Upvotes: 0
Views: 61
Reputation: 691645
Don't pass the class name of the sorter you want to use later. Don't pass the class either, because you wouldn't know how to instantiate it. Pass an instance of the sorter:
SomeSpecificSorter sorter = new SomeSpecificSorter()
CountryComponent cc = new CountryComponent(sorter);
and in the CountryComponent class:
private Comparator<Country> sorter;
public CountryComponent(Comparator<Country> sorter) throws IOException {
this.sorter = sorter;
getData();
Collections.sort(countriesList, sorter);
}
Upvotes: 3
Reputation: 1616
As an argument definition you should use
public CountryComponent(Class sorter) {
Object o = sorter.newInstance() ; // to call the default constructor
}
and call it by CountryComponent canvas = new CountryComponent(PopSorter.class);
An alternative is
public CountryComponent(String className) {
Class sorter = Class.forName(className);
Object o = sorter.newInstance() ; // to call the default constructor
}
and call it by CountryComponent canvas = new CountryComponent("yourpackages.PopSorter");
Upvotes: 0
Reputation: 4087
Pass the class, then you can use newInstance (assuming empty constructor)
public CountryComponent(Class<? extends Comparator> sorterClass)throws IOException
{
String sort = sorter;
getData();
Collections.sort(countriesList, sorterClass.newInstance());
}
Upvotes: 1