我正在使用一个我无法控制的外部库。 它需要我实现一个方法, 但我不知道如何返回所需的类型:
@Override
public Optional<Class<? extends AnInterface<?>>> getCustomClass() {
return Optional.of(MyClass.class);
// compiler is giving error at the above line:
// error: incompatible types: inference variable T has incompatible bounds
// equality constraints: Class<? extends AnInterface<?>>
// lower bounds: Class<MyClass>
// where T is a type-variable:
// T extends Object declared in method <T>of(T)
}
MyClass的:
public MyClass implements AnInterface<String> {
...
}
我也尝试过这个, 但它不起作用:
@Override
public Optional<Class<? extends AnInterface<?>>> getCustomClass() {
Optional<Class<? extends AnInterface<?>> clazz = MyClass.class;
// this time the compiler gives error at the above line:
// error: incompatible types: Class<MyClass> cannot be converted to Class<? extends AnInterface<?>>
return clazz;
}
还尝试了另一个不起作用的人:
@Override
public Optional<Class<? extends AnInterface<?>>> getCustomClass() {
Optional<Class<? extends AnInterface> clazz = MyClass.class;
return clazz;
// this time the compiler gives error at the above line:
// error: incompatible types: inference variable T has incompatible bounds
// equality constraints: Class<? extends PropertyEditor<?>>
// lower bounds: Class<CAP#1>
// where T is a type-variable:
// T extends Object declared in method <T>of(T)
// where CAP#1 is a fresh type-variable:
// CAP#1 extends PropertyEditor from capture of ? extends PropertyEditor
}
请知道如何退回自定义课程?
JDK版本:8u77
编辑:这些类是这样嵌套的:
public abstract class ParentClass<T> {
public abstract T method();
public class ImplementationClass implements ExternalLibraryInterface {
@Override
public Optional<Class<? extends AnotherExternalLibraryInterface<?>>> getCustomClass() {
return Optional.of(MyClass.class);
// compiler is giving error at the above line:
// error: incompatible types: inference variable T has incompatible bounds
// equality constraints: Class<? extends AnotherExternalLibraryInterface<?>>
// lower bounds: Class<MyClass>
// where T is a type-variable:
// T extends Object declared in method <T>of(T)
}
MyClass implements AnotherExternalLibraryInterface<String>{
...
}
}
}
因此,出于某种原因,在实现外部接口的重写方法时,编译器会被通配符搞糊涂。将所有类移动到自己的文件后,一切正常。
然而,@ Zefick的第一个解决方案实际上在嵌套类的情况下工作,我会将其标记为已解决:
return (Optional)(Optional.of(MyClass.class));
答案 0 :(得分:0)
转换为原始的可选类型有效但会发出警告。
public Optional<Class<? extends AnInterface<?>>> getCustomClass() {
return (Optional)(Optional.of(MyClass.class));
}
其他解决方案:
public Optional<Class<? extends AnInterface<?>>> getCustomClass() {
return Optional.<Class<? extends AnInterface<?>>>of(MyClass.class);
}