Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>From the few times that I came across this "need", it ultimately boils down to this construct:</p> <pre><code>public class Foo&lt;T&gt; { private T t; public Foo() { this.t = new T(); // Help? } } </code></pre> <p>This does work in C# assuming that <code>T</code> has a <em>default</em> constructor. You can even get the runtime type by <a href="http://msdn.microsoft.com/en-us/library/58918ffs.aspx" rel="noreferrer"><code>typeof(T)</code></a> and get the constructors by <a href="http://msdn.microsoft.com/en-us/library/system.type.aspx" rel="noreferrer"><code>Type.GetConstructor()</code></a>.</p> <p>The common Java solution would be to pass the <code>Class&lt;T&gt;</code> as argument.</p> <pre><code>public class Foo&lt;T&gt; { private T t; public Foo(Class&lt;T&gt; cls) throws Exception { this.t = cls.newInstance(); } } </code></pre> <p><em>(it does not necessarily need to be passed as constructor argument, as a method argument is also fine, the above is just an example, also the <code>try-catch</code> is omitted for brevity)</em></p> <p>For all other generic type constructs, the actual type can easily be resolved with a bit help of reflection. The below Q&amp;A illustrate the use cases and possibilities:</p> <ul> <li><a href="https://stackoverflow.com/questions/1942644/get-generic-type-of-java-util-list/">Get generic type of java.util.List</a></li> <li><a href="https://stackoverflow.com/questions/3941384/how-to-get-the-generic-type-at-runtime/">How to get the generic type at runtime?</a></li> <li><a href="https://stackoverflow.com/questions/18707582/get-actual-type-of-generic-type-argument-on-abstract-superclass/">Get actual type of generic type argument on abstract superclass</a></li> </ul>
 

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