2

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?

1
  • 1
    as a side note, you don't need that suppresswarnings, use return obj.cast(cacheObj) instead. Commented Aug 17, 2012 at 16:13

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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); 

1 Comment

with an unavoidable SuppressWarnings.
1

You can try :

List<String> ipList = Util.inCache(List.class, title); 

Comments

1

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); 

Comments

1

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() ); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.