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

}

基本的に私の FrameViewer クラスでは、さまざまな並べ替え方法のオプションのメニューを提供しています。さまざまなコンパレータのクラス名を引数として渡す方法にこだわっています。

上記は私のテストでした。しかし、.sort(ob、コンパレーター) は、それがコンパレーター クラスの名前であると想定しています。

最初は、文字列が渡されるときに特定のクラス名を手動で入力するだけでした

元:CountryComponent canvas = new CountryComponent(PopSorter);

それから私はそれが終わることを望んでいたCollections.sort(countriesList, new PopSorter());

instanceOf についていくつか見たことがありますが、本当に理解できませんでした。

4

3 に答える 3

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);
}
于 2013-11-12T22:35:17.553 に答える
1

クラスを渡すと、 newInstance を使用できます(空のコンストラクターを想定)

public CountryComponent(Class<? extends Comparator> sorterClass)throws IOException
{
        String sort = sorter;
        getData(); 
        Collections.sort(countriesList, sorterClass.newInstance());
}
于 2013-11-12T22:33:22.337 に答える
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");

于 2013-11-12T22:34:33.607 に答える