I’ve been using Spark Java framework in which data can be retrieved from a session like this, without any explicit type cast:
User user = req.session().attribute("user");
Item item = req.session().attribute("item");
I can
The attribute
method of spark.Session
looks like this:
public <T> T attribute(String name) {
return this.session.getAttribute(name);
}
And the javax.servlet.http.HttpSession
:
Object getAttribute(String var1);
However when I try to reproduce this behaviour:
public class Main {
public static void main(String[] args) {
}
public static <T> T hello(String key) {
return wow(key);
}
public static Object wow(String key) {
return "";
}
}
I get an error:
java.lang.Object cannot be converted to T
How do I make my generic method work similarly to the attribute
method? So that I could do
String name = hello("name");
List<String> names = hello("allnames");