我有以下课程:

public class DataService {

  static <T> void load(Structure structure, String path, DataServiceType dataService) {
     //do smth
  }

  private interface DataServiceType<T> {
      //do smth
  }

  private static class DataServiceInteger implements DataServiceType<Integer> {
      //do smth
  }

  private static class DataServiceString implements DataServiceType<String> {
      //do smth
  }

}


我想在此添加以下两种方法:

public static void load(Structure<Integer> structure,String path) throws IOException {
    load(structure,path,new DataServiceInteger());
}
public static void load(Structure<String> structure,String path) throws IOException {
    load(structure,path,new DataServiceString());
}


但是两种方法的擦除方式相同。如何在不更改方法名称的情况下实现它?

编辑

我不准确。实现DataServiceType的类具有mathod:

void getDataFromString(String in, T out);


(它们是解析器)
从文件中读取数据是从DataService进行的,方法为static <T> void load(Structure structure, String path, DataServiceType dataService),所以Le.Rutte先生的解决方案对我来说不是好方法,因为我不得不重复自己的工作。是否可以针对我的问题实施berry的解决方案?

最佳答案

您已经发现,由于类型擦除,运行时将无法区分不同的方法。名称必须不同,或者参数必须不同。

但是,您使用static方法。我个人的选择是使用DataService的特定实例:

public interface DataService<T> {
     Structure<T> load(Path path);
}


public StringDataService implements DataService<String> {
    public Structure<String> load(Path path) {
        ...
    }
}

public IntDataService implements DataService<Integer> {
   public Structure<Integer> load(Path path) {
       ...
   }
}

关于java - 从Java中的文件加载数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50424564/

10-09 21:03