gpt4 book ai didi

java - 为什么在这种情况下,覆盖 Setter 方法不起作用

转载 作者:行者123 更新时间:2023-11-29 03:17:35 25 4
gpt4 key购买 nike

抱歉,关于标题,因为我找不到更好的标题,所以对标题的任何编辑都将不胜感激。

考虑这些类:

public interface GlobalDashlet {        
public Collection<? extends GlobalDashletSetting> getSettings();
public void setSettings(Collection<? extends GlobalDashletSetting> settings);

}

public class Dashlet implements GlobalDashlet {
private Collection<DashletSetting> settings;
public Collection<DashletSetting> getSettings(){
return settings;
}
//This Wont Work
public void setSettings(Collection<DashletSetting> settings) {
this.settings = settings;
}

//This Will Work
public Collection<DashletSetting> getSettings(){
return settings;
}
}


public class DashletSetting implements GlobalDashletSetting {
}

为什么覆盖 setter 方法(我的意思是我已经完成的方式)不会工作(dashlet 类提示未实现的方法)但覆盖 getter 方法有效?

我该如何解决?我也需要能够实现 setter 方法(就像我重写 getter 方法的方式),因为我必须使用 jackson 映射器序列化 Dashlet 类,而 Jackson 无法在没有附加信息的情况下确定运行时对象的实际类型在父类(super class)上。

最佳答案

原因是返回类型可能是covariant .

重写方法时,您始终可以返回更具体的类型(即子类型)。一个更容易理解的例子如下:

class NumberProvider {
Number getNumber() { return 1.23; }
}

class IntegerProvider extends NumberProvider {

// Returning a more specific type when overriding:
@Override
Integer getNumber() { return 42; }
}

类型Collection<DashletSetting>Collection<? extends GlobalDashletSetting> 的真子类型.请参阅有关 Which super-subtype relationships exist among instantiations of generic types? 的部分在泛型常见问题解答中。

对于二传手来说,这是行不通的。它不起作用的简短原因是:它不是类型安全的。违反类型安全的示例很容易找到,尽管乍一看似乎有点做作:

// This is the interface as it was defined:
public interface GlobalDashlet {
public void setSettings(Collection<? extends GlobalDashletSetting> settings);
}

public class Dashlet implements GlobalDashlet {
// Assume this was working:
public void setSettings(Collection<DashletSetting> settings) {

// Then you could add a "DashletSetting" here:
settings.add(new DashletSetting());
}
}

// But someone who CALLED this method may not have given it
// a Collection<DashletSetting>, but maybe a collection
// like Collection<SpecialGlobalDashletSetting>:
Collection<SpecialGlobalDashletSetting> settings = ...;
GlobalDashlet dashlet = new Dashlet();

// Based on the method signature that was defined in the interface,
// this would be possible:
dashlet.setSettings(settings);

// Now, the "settings" collection WOULD contain a simple "DashletSetting",
// although it should only contain "SpecialGlobalDashletSetting" instances
// This would cause a ClassCastException sooner or later

这个例子可能看起来有点困惑。同样,使用像 Number 这样的“简单”类型更直观。和 Integer ,但它归结为同一个问题:如果允许 setter 方法使用更具体的类型,则可能会违反类型安全。

关于java - 为什么在这种情况下,覆盖 Setter 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25618184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com