Java - 与列表的泛型 [英] Java - Generics with lists

查看:179
本文介绍了Java - 与列表的泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的缓存写了一个函数来检索一个特定的对象。

  @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;
}
}
返回null;


$ / code $ / pre

我正在使用它,像这样

  String s = inCache(String.class,title); 

但现在我的缓存中有一个字符串列表,我不能像这样使用它

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

问题在于 List< String> .class 。我对java很陌生,我该如何编写它? 你不能得到<$ c的类$ c> List< String> ,您的情况唯一的方法是:

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


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?

解决方案

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

这篇关于Java - 与列表的泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆