我有以下java类:
public class Test {
public static void doThings() {
List<WrappedTypeContainer> things = Stream.of(new ExampleType())
.map(Type::toValue)
.map(WrappedTypeContainer::new)
.collect(Collectors.toList());
}
public static class WrappedType<T extends Type<T>> {
T value;
public WrappedType(T value) {
this.value = value;
}
public static WrappedType of(Type value) {
return new WrappedType(value);
}
}
public interface Type<T extends Type<T>> {
default WrappedType toValue() {
return WrappedType.of(this);
}
}
public static class ExampleType implements Type<ExampleType> {}
public static class WrappedTypeContainer {
WrappedType<ExampleType> wrappedValue;
public WrappedTypeContainer(WrappedType<ExampleType> wrappedValue) {
this.wrappedValue = wrappedValue;
}
}
}
此代码无法编译。我知道问题是什么,toValue()
方法返回一个原始类型而不是正确类型的参数。如果我改变了代码将编译。
据我所知,它应该只是在运行时将其转换为期望的类型而不是在编译时失败。我的理解是正确的还是编译失败是正确的。如果是这样,有人可以向我解释为什么这不起作用,以及这是否是编译器中的错误?
我目前正在使用Java build 1.8.0_102-b14进行编译。不过我也尝试过其他新版本。