我有一个名为CacheRequestWrapper
的类,它有一个带有泛型类型的字段.它还有另一个Optional<Long>
型字段.当类成为泛型时,此可选字段的值将不再是Long
类型.相反,它将成为Object
型.
换句话说,当我将类设置为泛型时,泛型类型Optional
被删除,我不明白为什么.只有字段cacheReturnValue
应该是T
类型,但似乎T
类型也被分配给了Optional
.让我用下面的例子来解释为什么会出现这种情况:
public class CacheRequestWrapper<T> extends CacheWrapper {
private T cacheReturnValue;
private Optional<Long> requestingUserId;
public Optional<Long> getRequestingUserId() {
return requestingUserId;
}
public void setRequestingUserId(Optional<Long>requestingUserId) {
this.requestingUserId = requestingUserId;
}
//other Getters, setters
}
class Service{
//1.
private void myRawTypedMethod(CacheRequestWrapper cacheRequestWrapper) {
Long viewerId = cacheRequestWrapper.getRequestingUserId().get(); //This gives the compile error 'required type: Long, provided type Object'
}
//2.
private <T> void myGenericTypedMethod(CacheRequestWrapper<T> cacheRequestWrapper) {
Long viewerId = cacheRequestWrapper.getRequestingUserId().get(); //No compile error here.
}
}
在方法1.
中,当我将可选值赋给viewerId
时,我会得到一个编译错误.
那么为什么Optional
字段的泛型类型会被泛型类型T
覆盖呢?