我搞不懂为什么这段代码不能编译.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Generic {
public static void main(String[] args) {
//List of imputs
List<Test> tests = new ArrayList<>();
tests.add(new TestSub1());
tests.add(new TestSub2());
// Processors are in a Map
Map<String, Processor<? extends Test>> testMaps = new HashMap<>();
testMaps.put("Processor1", new Processor1());
testMaps.put("Processor2", new Processor2());
// Doesn't compile
// java: incompatible types: Generic.Test cannot be converted to capture#1 of ? extends Generic.Test
tests.stream().filter(t -> t instanceof TestSub1)
.forEach(test ->
testMaps.get("Processor1").doWork(tests.get(0))
);
}
static class Test {
}
static class TestSub1 extends Test {
}
static class TestSub2 extends Test {
}
static abstract class Processor<T extends Test> {
abstract void doWork(T t);
}
// Processors can handle subclasses of Test
static class Processor1 extends Processor<TestSub1> {
@Override
void doWork(TestSub1 testSub1) {
System.out.println("processing testSub1");
}
}
static class Processor2 extends Processor<TestSub2> {
@Override
void doWork(TestSub2 testSub2) {
System.out.println("processing testSub2");
}
}
}
我想有每个测试的子类处理器.我试图将Tests.get(0)转换为TestSub1,但也不起作用.有没有可能这样做,或者我怎样才能使我的处理器类型安全和通用.
谢谢!