title: Java generics and numeric types
body: <p>I'd like to create a generic method which does effectively this:</p>
  
  <pre><code>class MyClass {
  
      static &lt;T extends Number&gt; T sloppyParseNumber(String str) {
          try {
              return T.valueOf(str);
          } catch (Exception e) {
              return (T)0;
          }
      }
  }
  </code></pre>
  
  <p>Now above does not compile for two reasons: there's no <code>Number.valueOf()</code> method and 0 can't be cast to <code>T</code>.</p>
  
  <p>Example usage:</p>
  
  <pre><code>String value = "0.00000001";
  
  System.out.println("Double: " + MyClass.&lt;Double&gt;sloppyParseNumber(value));
  System.out.println("Float: " + MyClass.&lt;Float&gt;sloppyParseNumber(value));
  
  double d = MyClass.sloppyParseNumber(value);
  float f = MyClass.sloppyParseNumber(value);
  </code></pre>
  
  <p>Is implementing above generic method possible with Java?  If yes, how?  If no, what's a good alternative approach?</p>
  
  <hr>
  
  <p>Edit: there seems to be a few possible duplicates, but I did not find one, which covers exactly this. I'm hoping there's some trick to pull, which would allow these two operations: parse string to a <code>Number</code> subclass, and return 0 value for a <code>Number</code> subclass.</p>