[英]Why doesn't the Java compiler flag this as an error?
我在Java Web应用程序中创建了一个枚举类型,作为抽象一种将对象添加到会话属性的过程的方式。 如果我尝试将错误的对象类型映射到特定键,则会引发错误。 枚举代码如下所示:
public enum SessionVariables
{
CURRENT_BRIEF {
@Override
public <Briefable> void setValue(Briefable item)
{
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(this.toString(), item);
}
@Override
@SuppressWarnings("unchecked")
public <Briefable> Briefable getValue()
{
return (Briefable) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(this.toString());
}
};
public abstract <T> void setValue(T item);
public abstract <T> T getValue();
}
到目前为止一切正常,没有编译问题。
但是,如果我实际上尝试使用错误类型的方法,则编译器不会发现任何错误,例如:
SessionVariables.CURRENT_BRIEF.setValue("String value");
正常编译。
任何想法为什么会这样? 我错过了什么吗? 我在Windows 7计算机上使用Java SE 8,EE7。
CURRENT_BRIEF
的声明类型为SessionVariables
。 该类型具有方法<T> void setValue(T item)
并且您的方法调用符合该签名。
此外,当你写
public <Briefable> void setValue(Briefable item)
您基本上重申了同一件事,只是将类型参数命名为Briefable
。 实际类型仍将从调用上下文中推断出来,这意味着Briefable
将该调用解析为String
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.