title: java: How can I do dynamic casting of a variable from one type to another?
body: <p>I would like to do dynamic casting for a Java variable, the casting type is stored in a different variable.</p>
  
  <p>This is the regular casting:</p>
  
  <pre><code> String a = (String) 5;
  </code></pre>
  
  <p>This is what I want:</p>
  
  <pre><code> String theType = 'String';
   String a = (theType) 5;
  </code></pre>
  
  <p>Is this possible, and if so how? Thanks!</p>
  
  <h1>Update</h1>
  
  <p>I'm trying to populate a class with a <code>HashMap</code> that I received.</p>
  
  <p>This is the constructor:</p>
  
  <pre><code>public ConnectParams(HashMap&lt;String,Object&gt; obj) {
  
      for (Map.Entry&lt;String, Object&gt; entry : obj.entrySet()) {
          try {
              Field f =  this.getClass().getField(entry.getKey());                
              f.set(this, entry.getValue()); /* &lt;= CASTING PROBLEM */
          } catch (NoSuchFieldException ex) {
              log.error("did not find field '" + entry.getKey() + '"');
          } catch (IllegalAccessException ex) {
              log.error(ex.getMessage());         
          }
      }
  
  }
  </code></pre>
  
  <p>The problem here is that some of the class' variables are of type <code>Double</code>, and if the number 3 is received it sees it as <code>Integer</code> and I have type problem. </p>