title: Generic data type conversion method
body: <p>This question is in response to another question by <a href="https://stackoverflow.com/users/47633/opensas">opensas</a>: <a href="https://stackoverflow.com/questions/7061176/building-a-generic-initializer-function-in-java">building a generic initializer function in java</a></p>
  
  <p>From his question it became clear that he needs to convert from any data type <code>T1</code> to another type <code>T2</code>. When I say "data type" here, I mean types limited to those commonly used to represent raw data: <code>Integer</code>, <code>String</code>, <code>Date</code>, etc. For the purpose of this question we can consider primitives to be boxed.</p>
  
  <p>I'm wondering if there is any API that supports conversion between types where both the input and output are generalized to a set of supported data types. I had a look at <a href="http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/converters/package-summary.html" rel="nofollow noreferrer">Apache Commons' beanutils.converters package</a>, but there's a separate converter class for each known input. I'm looking for any functionality that implements something like the following signature:</p>
  
  <pre><code>static &lt;IN, OUT&gt; OUT convert(IN value, Class&lt;OUT&gt; targetType);
  </code></pre>
  
  <p>or else</p>
  
  <pre><code>static &lt;IN, OUT&gt; OUT convert(IN value, OUT defaultValue);
  </code></pre>
  
  <p>It really wouldn't be too hard to implement this kind of mapping oneself, either using a bunch of <code>else if</code> blocks pointing to the various Commons Converters, or else a <code>Map&lt;Class&lt;?&gt;, Converter&gt;</code> for the same purpose. But I'm wondering if this kind of functionality is supported somewhere.</p>
  
  <p>Also, if this winds up being a duplicate I apologize. I tried finding similar questions and was surprised when I found none matching this situation.</p>
  
  <p><strong>EDIT:</strong> so an example of this code in action would be:</p>
  
  <pre><code>Integer i = GenericConverter.convert("123", Integer.class);    //returns 123
  Date d = GenericConverter.convert(1313381772316L, Date.class); //returns today's date
  Boolean b = GenericConverter.convert(0, Boolean.class);        //returns false
  Long l = GenericConverter.convert("asdf", Long.class);         //RuntimeException
  </code></pre>
  
  <p><strong>UPDATE:</strong> The BalusC code I linked falls close to the mark, and Bohemian's answer is a nice lightweight solution (although it doesn't work for Boolean conversions). He's also right that Dates should be probably be handled separately if we want to generalize conversion of these other data types. I'm still hoping for additional answers though - especially if there is more of a hands-off API available somewhere.</p>