[英]Why doesn't the Java compiler flag this as an error?
I have created an enumerated type in my Java webapp as a way of abstracting the procedure of adding objects to the session attributes. 我在Java Web应用程序中创建了一个枚举类型,作为抽象一种将对象添加到会话属性的过程的方式。 The idea being to precipitate an error if I try and map the wrong object type to a particular key.
如果我尝试将错误的对象类型映射到特定键,则会引发错误。 The enum code looks like this:
枚举代码如下所示:
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();
}
All fine so far, no compilation problems. 到目前为止一切正常,没有编译问题。
However, if I actually try and use the methods with a wrong type, no error is found by the compiler, for instance: 但是,如果我实际上尝试使用错误类型的方法,则编译器不会发现任何错误,例如:
SessionVariables.CURRENT_BRIEF.setValue("String value");
compiles normally. 正常编译。
Any ideas why this is the case? 任何想法为什么会这样? Have I missed something out?
我错过了什么吗? I'm using Java SE 8, EE7 on a Windows 7 machine.
我在Windows 7计算机上使用Java SE 8,EE7。
The declared type of CURRENT_BRIEF
is SessionVariables
. CURRENT_BRIEF
的声明类型为SessionVariables
。 That type has the method <T> void setValue(T item)
and your method invocation complies with that signature. 该类型具有方法
<T> void setValue(T item)
并且您的方法调用符合该签名。
Furthermore, when you wrote 此外,当你写
public <Briefable> void setValue(Briefable item)
you basically restated the same thing, just naming your type parameter Briefable
. 您基本上重申了同一件事,只是将类型参数命名为
Briefable
。 The actual type will still be inferred from the calling context, which means that Briefable
resolves to String
for that invocation. 实际类型仍将从调用上下文中推断出来,这意味着
Briefable
将该调用解析为String
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.