title: Convert java legacy code to generic - how to replace Object with type?
body: <p>// legacy code</p>
  
  <pre><code>void setCacheValue(String name, Object value){
      getServletContext().setAttribute(name, value);
  }
  Object getCacheValue(String name){
      return getServletContext().getAttribute(name);
  }
  </code></pre>
  
  <p>// so I want to use generic for "type safety"</p>
  
  <pre><code>// first, set method seems working perfectly
  &lt;T&gt; void setCacheObject(String name, T value){
      getServletContext().setAttribute(name, value);
  }
  </code></pre>
  
  <p>// then, here comes the trouble</p>
  
  <pre><code>&lt;T&gt; 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?
  }
  </code></pre>
  
  <p>// This is what I what to achieve in my <em>clean</em> calling code:</p>
  
  <pre><code>{
      double x = 1.2;
      setCacheValue("x", x);
      //...
      // later
      Double value = getCacheValue("x");
      // too bad cannot use primitive type - it cannot handle null
  </code></pre>
  
  <p>}</p>
  
  <p>So, what is the correct way of doing this?</p>