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
Just to clarify Joe's answer ( I don't have enough reputation to comment), at runtime there is no difference between a List <String>
and List<Integer>
or any other type of List
, generics aren't kept at runtime.
Meaning, List<String>.class
is completely identical to List<Integer>.class
and is actually List.class
. This is a weakness of the Java type system. I'm not familiar with a simple way to implement what you wish for.
A code proof for the heck of it :
// It is true that
List<String> stringList = new ArrayList<String>();
List<Integer> integerList = new ArrayList<Integer>();
System.out.println( stringList.getClass() == integerList.getClass() );
// And that ...
List objectList = new ArrayList();
System.out.println( stringList.getClass() == objectList.getClass() );
//However, the following is false because a different implementation is used ( I wanted a false case)
List objectLinkedList = new LinkedList();
System.out.println( objectLinkedList.getClass() == objectList.getClass() );
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);
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 try :
List<String> ipList = Util.inCache(List.class, title);
Try this-
List<String> inList = (List<String>)Test.inCache(List.class, title);
And you can do also -
List<String> inList = Test.inCache((Class<? extends List<String>>)List.class, token);