Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Due to <a href="http://docs.oracle.com/javase/tutorial/java/generics/erasure.html">type erasure</a>, you can't instantiate generic objects. Normally you could keep a reference to the <code>Class</code> object representing that type and use it to call <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29"><code>newInstance()</code></a>. However, this only works for the default constructor. Since you want to use a constructor with parameters, you'll need to look up the <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Constructor.html"><code>Constructor</code></a> object and use it for the instantiation:</p> <pre><code>protected &lt;T&gt; T getProperty(String key, T fallback, Class&lt;T&gt; clazz) { String value = properties.getProperty(key); if (value == null) { return fallback; } else { //try getting Constructor Constructor&lt;T&gt; constructor; try { constructor = clazz.getConstructor(new Class&lt;?&gt;[] { String.class }); } catch (NoSuchMethodException nsme) { //handle constructor not being found } //try instantiating and returning try { return constructor.newInstance(value); } catch (InstantiationException ie) { //handle InstantiationException } catch (IllegalAccessException iae) { //handle IllegalAccessException } catch (InvocationTargetException ite) { //handle InvocationTargetException } } } </code></pre> <p>However, seeing how much trouble it is to achieve this, including the performance cost of using reflection, it's worth looking into other approaches first. </p> <p>If you absolutely need to take this route, and if <code>T</code> is limited to a distinct set of types known at compile time, a compromise would be to keep a static <code>Map</code> of <code>Constructor</code>s, which is loaded at startup - that way you don't have to dynamically look them up at every call to this method. For example a <code>Map&lt;String, Constructor&lt;?&gt;&gt;</code> or <code>Map&lt;Class&lt;?&gt;, Constructor&lt;?&gt;&gt;</code>, which is populated using a <a href="http://download.oracle.com/javase/tutorial/java/javaOO/initial.html">static block</a>.</p>
 

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