title: Java generics and typecasting
body: <p>I have a badly created container object that holds together values of different java types(String, Boolean etc ..)</p>
  
  <pre><code>public class BadlyCreatedClass {
      public Object get(String property) {
          ...;
      }
  };
  </code></pre>
  
  <p>And we extract values from it in this way</p>
  
  <pre><code>String myStr = (String) badlyCreatedObj.get("abc");
  Date myDate = (Date) badlyCreatedObj.get("def");
  </code></pre>
  
  <p>I am forced to write some new code using this object and I am trying to see if there is clean way to do this. More specifically which method from the below is preferred ?</p>
  
  <p><strong>Explicit Cast</strong></p>
  
  <pre><code>String myStr = (String) badlyCreatedObj.get("abc")
  Date myDate = (Date) badlyCreatedObj.get("def");
  </code></pre>
  
  <p><strong>Using generic cast</strong></p>
  
  <pre><code>public &lt;X&gt; X genericGet(String property) {
  
  }
  
  public String getString(String property) { 
  return genericGet(property); 
  }
  
  public Date getDate(String property) { 
  return genericGet(property); 
  }
  </code></pre>
  
  <p><strong>Using Class.cast</strong></p>
  
  <pre><code>&lt;T&gt; T get(String property, Class&lt;T&gt; cls) {
      ;
  }
  </code></pre>
  
  <p>I have gone through several related questions on SO <a href="https://stackoverflow.com/questions/1959022/java-generic-function-how-to-return-generic-type">Java generic function: how to return Generic type</a> , <a href="https://stackoverflow.com/questions/2669326/java-generic-return-type">Java generic return type</a> all of them seem to say the such typecasting is dangerous, ALthough I dont see much difference between the three, given this which method would you prefer ?</p>
  
  <p>Thanks</p>