将类名称作为参数传递,以后用作参数

时间:2013-11-12 22:28:33

标签: java

public CountryComponent(String sorter)throws IOException
{
    String sort = sorter;
    getData(); 
    Collections.sort(countriesList, new sort());

}

基本上在我的FrameViewer类中我提供了一个用于不同排序方法的选项菜单,我坚持如何传递我的不同比较器的类名作为参数

以上是我的考试。但.sort(ob,比较器)期望它是比较器类的名称

我原本只是手动输入特定的类名作为传递的字符串

ex:CountryComponent canvas = new CountryComponent(PopSorter);

然后我希望它最终成为Collections.sort(countriesList, new PopSorter());

我看到了关于instanceOf的一些事情,但我真的不理解它,我不太确定他们想要做什么正是我想要做的事情

3 个答案:

答案 0 :(得分:3)

不要传递稍后要使用的分拣机的类名。也不要通过这个类,因为你不知道如何实例化它。传递分拣机的实例:

SomeSpecificSorter sorter = new SomeSpecificSorter()
CountryComponent cc = new CountryComponent(sorter);

并在CountryComponent类中:

private Comparator<Country> sorter;

public CountryComponent(Comparator<Country> sorter) throws IOException {
    this.sorter = sorter;
    getData(); 
    Collections.sort(countriesList, sorter);
}

答案 1 :(得分:1)

传递类,然后你可以使用newInstance(假设为空构造函数)

public CountryComponent(Class<? extends Comparator> sorterClass)throws IOException
{
        String sort = sorter;
        getData(); 
        Collections.sort(countriesList, sorterClass.newInstance());
}

答案 2 :(得分:0)

作为参数定义,您应该使用

public CountryComponent(Class sorter) {
  Object o = sorter.newInstance() ; // to call the default constructor
}

并通过CountryComponent canvas = new CountryComponent(PopSorter.class);

进行调用

另一种选择是

public CountryComponent(String className) {
  Class sorter = Class.forName(className);
  Object o = sorter.newInstance() ; // to call the default constructor
}

并通过CountryComponent canvas = new CountryComponent("yourpackages.PopSorter");

进行调用
相关问题