I wrote a function for my cache to retrieve a specific object. This way I don't need to cast it .
@SuppressWarnings("unchecked")
public static <T> T inCache(Class<T> obj, String token) {
Object cacheObj = Cache.get(token);
if (cacheObj != null) {
if (obj.isAssignableFrom(cacheObj.getClass())) {
return (T) cacheObj;
}
}
return null;
}
I am using it like this
String s = inCache(String.class, title);
But now I have a list of Strings in my cache and I can't use it like this
List<String> ipList = Util.inCache(List<String>.class, title);
The problem is the List<String>.class . I am very new to java, how do I have to write it?
There is a concept in java called type erasure. Due to legacy reasons, something like List is just a list. It doesn't remember that it is a list of string at run time. You should just write List.class.
You can then specify the type of object in the List when iterating through it.
You can't get class of List<String>, in your case the only way is:
List<String> ipList = (List<String>)Util.inCache(List.class, title);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With