title: Java: Dynamically cast Object reference to reference's class?
body: <p>Is it possible to cast a variable using a different variable instead of using the name of a class?</p>
  
  <p>Here is functioning code:</p>
  
  <pre><code>Object five = new Integer(5);
  int six = (Integer) five + 1;
  </code></pre>
  
  <p>I would love to replace that second line with</p>
  
  <pre><code>int six = five + 1;
  </code></pre>
  
  <p>but I can't, so could i do something like one of these alternatives:</p>
  
  <pre><code>int six = (foo) five + 1;
  int six = foo(five) + 1;
  int six = foo.cast(five) + 1;
  </code></pre>
  
  <p>??</p>
  
  <p><i> why i want to do this </i><br>
  I have a Map with keys of a custom enum, and with values of type String, Integer, Double, etc.</p>
  
  <p>I would like to perform class-specific operations on map entry values <i>without</i> hard-coding the cast class. </p>
  
  <p><i>example</i></p>
  
  <pre><code>enum keyEnum { height, color; }
  
  public static void main(String[] args) {
      Map&lt;keyEnum, Object&gt; map= new HashMap();
      String value1 = "red";
      Double value2 = 3.2;
      map.put(keyEnum.color, value1);
      map.put(keyEnum.height, value2);
  
      double x = (Double) map.get(keyEnum.height) + 10.5;
  }
  </code></pre>
  
  <p>I would really like to avoid having to hard-code that <code>(Double)</code> in the last line. Have found no solutions so far, only indications that it might not be possible.</p>
  
  <p>I'm using this setup for a program that needs to write and read and write large csv files.  I would like a way for Java to automatically cast variables appropriately so I don't have to remember or code the class of every column type.  </p>
  
  <p>I have an enum of all the column titles which i use as keys for maps that store the column's variables.  This is to avoid hard-coding the array index for each column (after row.split(",")) which is a maintenance nightmare.  I'm open to better approaches to this</p>