Kevin Knapp
Kevin Knapp

Reputation: 53

passing along a Class name as a argument, to be used as a argument later on

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

Answers (3)

JB Nizet
JB Nizet

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

GerritCap
GerritCap

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

Taylor
Taylor

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

Related Questions