Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Generics with lists

Tags:

java

generics

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?

like image 346
Maik Klein Avatar asked Dec 21 '25 11:12

Maik Klein


2 Answers

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.

like image 116
Joe Avatar answered Dec 23 '25 01:12

Joe


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);
like image 26
ice Avatar answered Dec 22 '25 23:12

ice