//传统代码

void setCacheValue(String name, Object value){
    getServletContext().setAttribute(name, value);
}
Object getCacheValue(String name){
    return getServletContext().getAttribute(name);
}

//因此,我想使用通用来进行“类型安全”

// first, set method seems working perfectly
<T> void setCacheObject(String name, T value){
    getServletContext().setAttribute(name, value);
}

//然后,麻烦来了

<T> T getCacheValue(String name){    
    // of course, I cannot change servlet class - it returns Object type
    Object value = getServletContext().getAttribute(name);
    // would this work:     
    return  (T) value;
    // this cast is meaningless... but how should I do it?
}

//这就是我要实现的目标 干净的 通话代码:

{
    double x = 1.2;
    setCacheValue("x", x);
    //...
    // later
    Double value = getCacheValue("x");
    // too bad cannot use primitive type - it cannot handle null

}

那么,这样做的正确方法是什么?

有帮助吗?

解决方案

这确实是不可能的。您需要通过“混凝土” T 以某种方式作为方法参数,以便在运行时已知实际类型。常用的方法是将其传递给 Class<T>, ,以便您可以使用 Class#cast():

<T> T getCacheValue(String name, Class<T> type) {
    return type.cast(getServletContext().getAttribute(name));
}

您可以按以下方式使用它:

Double value = getCacheValue("x", Double.class);

其他提示

MAP GENRICS支持地图所有值的类型,而不是针对特定值的不同类型。您可以看到如何伪造它 这里. 。基本上,您的想法是您必须在键上具有类型安全性,在该密钥上,键在其上具有通用类型,而其存在仅与该值相关联。

归根结底您的班级用户。

实际上,也要编译:

public class Test
{
    <T> T getCacheValue(String name){    
        // of course, I cannot change servlet class - it returns Object type
        Object value = getServletContext().getAttribute(name);
        // would this work:     
        return  (T) value;
        // this cast is meaningless... but how should I do it?
    }

    public static void main(String... args)
    {
        Test t = new Test();
        Double double = t.<Double>getCacheValue("Double");
    }
}

这有点毫无意义(也许如果您添加了Typecheck),但我发现很有趣。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top