public static <T> T inCache(T obj) throws ClassNotFoundException {
String[] token = validateCookie(); //gives me to strings
if (token == null)
return null;
if (Cache.get(token[0]) != null) {
if (Cache.get(token[0]).getClass() == Class.forName(token[1])
&& obj.getClass() == Cache.get(token[0]).getClass()) {
T test = (T) Cache.get(token[0]);
return test;
}
}
return null;
}
The code above is completely wrong.
Basicly I want to do something like this:
- I want to set the class in my function. for example
inCache<User>(); -
check if the object that i get out of my cache has the same class that i have specified before.
(obj.getClass == User.class) -
If the classes matches , cast the object to the class and return it.
return (User)obj
I want to use it like this.
User user = inCache<User>();
As for the class signature, why don’t you use something like this:
And then call it like this:
Generics can’t be used the way you described (
User user = inCache<User>();) due to type erasure at runtime, i.e. the type ofTis unknown at runtime in that case.Also note that it might be better to test using
Class#isAssignableFrom(...)to be able to check for subclasses as well, e.g.clazz.isAssignableFrom(Cache.get(token[0]).getClass()). That way you could pass an interface or super class and still get a match if the object is of a subtype.