我正在尝试在HashMap中存储字符串到函数的映射,我正在努力使输入正确.如何存储通用功能接口定义的各种类型的功能?
这是相关的代码.
@FunctionalInterface
public interface Converter<F,T> {
T convert(F from);
}
HashMap<String, Converter<?, ?>> fooMapping= new HashMap<String, Converter<?, ?>>();
fooMapping.put("name", (someString) -> someString);
fooMapping.put("flavor", (someInt) -> someAge + 1);
Run Code Online (Sandbox Code Playgroud)
最后两行不能使用以下(明显)错误进行编译:
- 方法length()未定义类型
Object-操作符+未定义参数类型Object,int
所以我的问题是当我在我的hashmap中存储lamda时如何指定转换器的TYPES F和T所以我不会被迫从Object转换所有内容?
我试图了解如何在接口中以有界类型参数的形式使用泛型.在这种情况下,为了避免在具体实现中使用有界参数时进行转换,但我遇到了问题.我将使用以下示例来说明我的问题:
有一个接口和两个具体的实现
public abstract class Publication {
}
public class Newspaper extends Publication {
}
public class Newspaper extends Publication {
}
Run Code Online (Sandbox Code Playgroud)
然后我们有一个界面代表一个出版社,有两个具体实现,一个发布杂志和其他报纸
public interface Publisher {
public <T extends Publication >void publish(T publication);
}
Run Code Online (Sandbox Code Playgroud)
这是两个实现
//DOES NOT COMPILE
public class MagazinePublisher implements Publisher{
@Override
public void publish(Magazine publication) {
//do something with the magazine, its already the type we need without casting
}
}
//COMPILES but a cast is required to get the type I want
public class NewsPaperPublisher …Run Code Online (Sandbox Code Playgroud)