Convert legacy java code to generic - how to replace an object with a type?

// outdated code

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

// therefore I want to use generic for "type security"

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

//, then there is a problem

<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?
}

// This is what I need to do in my clean code:

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

}

So what is the right way to do this?

+3
source share
3 answers

This is really impossible. You need to pass "concrete" Tsomehow as an argument to the method so that the actual type is known at runtime. The commonly used approach passes it as Class<T>, so you can use Class#cast():

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

You can use it as follows:

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

, . , . , , , .

, , , , typeafe .

0

Actually, this also compiles:

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

This is useless (maybe if you add typecheck), but I was interested to know.

0
source

Source: https://habr.com/ru/post/1744387/


All Articles