I’ve been using Spark Java framework in which data can be retrieved from a session like this, without any explicit type cast:
<code>User user = req.session().attribute("user");
Item item = req.session().attribute("item");
</code>
<code>User user = req.session().attribute("user");
Item item = req.session().attribute("item");
</code>
User user = req.session().attribute("user");
Item item = req.session().attribute("item");
I can
The attribute
method of spark.Session
looks like this:
<code> public <T> T attribute(String name) {
return this.session.getAttribute(name);
}
</code>
<code> public <T> T attribute(String name) {
return this.session.getAttribute(name);
}
</code>
public <T> T attribute(String name) {
return this.session.getAttribute(name);
}
And the javax.servlet.http.HttpSession
:
<code> Object getAttribute(String var1);
</code>
<code> Object getAttribute(String var1);
</code>
Object getAttribute(String var1);
However when I try to reproduce this behaviour:
<code>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 "";
}
}
</code>
<code>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 "";
}
}
</code>
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:
<code>java.lang.Object cannot be converted to T
</code>
<code>java.lang.Object cannot be converted to T
</code>
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
<code>String name = hello("name");
List<String> names = hello("allnames");
</code>
<code>String name = hello("name");
List<String> names = hello("allnames");
</code>
String name = hello("name");
List<String> names = hello("allnames");