title: What's the correct method signature for getting the cause of an exception, typecast to the correct type?
body: <p>I have a method getInstanceOfCause() that accepts an exception class and a Throwable, iterates through the cause of the Throwable and it's causes and returns the instance of the cause that matches the class passed as the first parameter. It looks like this:</p>
  
  <pre><code>public class ExceptionUtil {
      public static &lt;T&gt; T getInstanceOfCause(Class&lt;? extends Throwable&gt; expected, Throwable exc) {
          return (expected.isInstance(exc)) ? (T) exc : getInstanceOfCause(expected, exc.getCause());
      }
  }
  </code></pre>
  
  <p>Let's assume that the expected type is indeed in the "cause-chain" and the call won't cause a NPE. I am able to use it so:</p>
  
  <pre><code>MyException myException = ExceptionUtil.&lt;MyException&gt;getInstanceOfCause(MyException.class, exception);
  </code></pre>
  
  <p>This is awkward as I have to specify the type twice. Is there any way to rewrite the method signature so that I can use it like below, while still ensuring at compile time that the type is a subclass of Throwable?</p>
  
  <pre><code>MyException myException = ExceptionUtil.getInstanceOfCause(MyException.class, exception);
  </code></pre>
  
  <p>or</p>
  
  <pre><code>MyException myException = ExceptionUtil.&lt;MyException&gt;getInstanceOfCause(exception);
  </code></pre>