作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下类(class):
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 的类具有方法:
void getDataFromString(String in, T out);
(他们是解析器)从文件中读取的内容保存在方法 static <T> void load(Structure structure, String path, DataServiceType dataService)
中来自 DataService,所以 M. le Rutte 的解决方案对我来说不太好,因为我必须重复一遍。是否可以针对我的问题实现 berry 的解决方案?
最佳答案
正如您已经发现的,由于类型删除,运行时将无法区分不同的方法。名称必须不同,或者参数必须不同。
但是,您使用静态
方法。我个人的选择是使用 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/
我是一名优秀的程序员,十分优秀!