java&接口方法中的上界参数
我有一个包含映射函数的散列映射,它将X1类型的特定实例转换为X2类型的特定实例。X1的类对象用作此映射的键。示例代码:java&接口方法中的上界参数,java,generics,Java,Generics,我有一个包含映射函数的散列映射,它将X1类型的特定实例转换为X2类型的特定实例。X1的类对象用作此映射的键。示例代码: public class Application { interface X1 {} static class A1 implements X1 {} static class B1 implements X1 {} interface X2 {} static class A2 implements X2 {} static
public class Application {
interface X1 {}
static class A1 implements X1 {}
static class B1 implements X1 {}
interface X2 {}
static class A2 implements X2 {}
static class B2 implements X2 {}
@FunctionalInterface
interface Mapper<T extends X1> {
X2 convert(T from);
}
public static void main(String[] args) {
Map<Class<? extends X1>, Mapper<? extends X1>> map = new HashMap<>();
map.put(A1.class, (A1 x1) -> /* some logic */ new A2());
map.put(B1.class, (B1 x1) -> /* some logic */ new B2());
X1 input = new A1();
Mapper<? extends X1> mapperFunction = map.get(input.getClass());
X2 output = mapperFunction.convert(input); // <- Required type: capture of ? extends X1, Provided: X1
}
}
是否可以修复所需的类型:捕获?扩展X1,前提是:X1错误而不将mapperFunction强制转换为Mapper?我建议按以下方式更改代码,希望这有助于解决您的任务:
public class Application {
interface X1 {}
static class A1 implements X1 {}
static class B1 implements X1 {}
interface X2 {}
static class A2 implements X2 {}
static class B2 implements X2 {}
@FunctionalInterface
interface Mapper {
X2 convert(X1 from);
}
public static void main(String[] args) {
Map<Class<? extends X1>, Mapper> map = new HashMap<>();
map.put(A1.class, (X1 x1) -> /* some logic */ new A2());
map.put(B1.class, (X1 x1) -> /* some logic */ new B2());
X1 input = new A1();
Mapper mapperFunction = map.get(input.getClass());
X2 output = mapperFunction.convert(input);
}
}
你必须投。要么在地图绘制程序中,要么在你得到它之后。