[英]Generic issues: T extends interface type. Cannot call method to return an object which extends the type?
我在父类中声明了此方法:
protected <ConfigT extends LoadableConfig> ConfigT getConfig(final String configId) {
return (ConfigT)getConfigService().getConfig(configId, getDriver());
}
配置服务方法定义如下:
@SuppressWarnings("unchecked")
@Override
public <ConfigT extends LoadableConfig> ConfigT getConfig(String configId, WebDriver driver) {
//noinspection unchecked
Map<String,LoadableConfig> profile = profiles.get(getProfileName(driver));
if(profile != null) {
return (ConfigT) profile.get(configId);
}
return null;
}
我想要的配置类型在这里:
public interface AccessibleConfig extends LoadableConfig, PolleableConfig {
....
}
这行代码引发了不兼容的类型错误:
AccessibleConfig config = getConfig(ValidationPane.class.getCanonicalName());
这怎么可能? AccessibleConfig
扩展了LoadableConfig
。 称为的方法声明该返回类型是扩展LoadableConfig
某种类型。 我正在运行jdk1.8.0_102.jdk。 在IntelliJ中以及从命令行使用Maven进行编译时都会发生此故障。 我可以使用扩展了LoadableConfig
类型的其他配置类型来执行此操作。
编辑:
家长班:
public abstract class AbstractLoadable<T extends AbstractLoadable<T>> {
private Map<String,LoadableConfig> profiles = new HashMap<>();
protected <T extends LoadableConfig> T getConfig(final String configId) {
return (T) profiles.get(configId);
}
}
具体课程:
public class ConcreteLoadable extends AbstractLoadable {
public ConcreteLoadable(final String profileName) {
AccessibleConfig config = getConfig(ConcreteLoadable.class.getCanonicalName());
}
}
以及接口类型:
public interface LoadableConfig {
Integer getLoadTimeoutInSeconds();
void setLoadTimeoutInSeconds(final Integer loadTimeoutInSeconds);
}
public interface AccessibleConfig extends LoadableConfig {
Boolean getHoverOverAccessorWithJavascript();
void setHoverOverAccessorWithJavascript(final Boolean hoverOverAccessorWithJavascript);
Boolean getClickAccessorWithJavascript();
void setClickAccessorWithJavascript(final Boolean clickAccessorWithJavascript);
}
因此,产生此最小示例的练习实际上使识别编译器错误的根源变得非常容易。 我在下面发布了这个问题的答案。 我谦卑地接受我实际上并没有最初发表一个完整的例子。
我发现了问题。 具体类需要将自身传递给父类,因为父类是自反通用的。 该错误消息并不是超级有用,因此我被束缚在考虑父类方法的通用参数而不是应用于父类本身的通用参数上。
需要将ConcreteLoadable
的类声明更改为此,以摆脱编译错误:
public class ConcreteLoadable extends AbstractLoadable<ConcreteLoadable> {
public ConcreteLoadable(final String profileName) {
AccessibleConfig config = getConfig(ConcreteLoadable.class.getCanonicalName());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.