James Hamilton
James Hamilton

Reputation: 457

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. 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.

Upvotes: 0

Views: 75

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200246

The declared type of CURRENT_BRIEF is SessionVariables. That type has the method <T> void setValue(T item) and your method invocation complies with that signature.

Furthermore, when you wrote

public <Briefable> void setValue(Briefable item)

you basically restated the same thing, just naming your type parameter Briefable. The actual type will still be inferred from the calling context, which means that Briefable resolves to String for that invocation.

Upvotes: 3

Related Questions