Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is a small loophole however: if you define your <code>Foo</code> class as abstract. That would mean you have to instantiate you class as:</p> <pre><code>Foo&lt;MyType&gt; myFoo = new Foo&lt;MyType&gt;(){}; </code></pre> <p>(Note the double braces at the end.)</p> <p>Now you can retrieve the type of <code>T</code> at runtime:</p> <pre><code>Type mySuperclass = myFoo.getClass().getGenericSuperclass(); Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0]; </code></pre> <p>Note however that <code>mySuperclass</code> has to be the superclass of the class definition actually defining the final type for <code>T</code>.</p> <p>It is also not very elegant, but you have to decide whether you prefer <code>new Foo&lt;MyType&gt;(){}</code> or <code>new Foo&lt;MyType&gt;(MyType.class);</code> in your code.</p> <hr> <p>For example:</p> <pre><code>import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayDeque; import java.util.Deque; import java.util.NoSuchElementException; /** * Captures and silently ignores stack exceptions upon popping. */ public abstract class SilentStack&lt;E&gt; extends ArrayDeque&lt;E&gt; { public E pop() { try { return super.pop(); } catch( NoSuchElementException nsee ) { return create(); } } public E create() { try { Type sooper = getClass().getGenericSuperclass(); Type t = ((ParameterizedType)sooper).getActualTypeArguments()[ 0 ]; return (E)(Class.forName( t.toString() ).newInstance()); } catch( Exception e ) { return null; } } } </code></pre> <p>Then:</p> <pre><code>public class Main { // Note the braces... private Deque&lt;String&gt; stack = new SilentStack&lt;String&gt;(){}; public static void main( String args[] ) { // Returns a new instance of String. String s = stack.pop(); System.out.printf( "s = '%s'\n", s ); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload