Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I instantiate a generic type in Java?
    primarykey
    data
    text
    <p>I've added a human-readable configuration file to my app using <a href="http://download.oracle.com/javase/6/docs/api/java/util/Properties.html"><code>java.util.Properties</code></a> and am trying to add a wrapper around it to make type conversions easier. Specifically, I want the returned value to "inherit" it's type from the provided default value. Here's what I've got so far:</p> <pre class="lang-java prettyprint-override"><code>protected &lt;T&gt; T getProperty(String key, T fallback) { String value = properties.getProperty(key); if (value == null) { return fallback; } else { return new T(value); } } </code></pre> <p><a href="http://pastebin.com/CWpzFziJ">(Full example source.)</a></p> <p>The return value from <code>getProperty("foo", true)</code> would then be a boolean regardless of whether it was read from the properties file and similarly for strings, integers, doubles, &amp;c. Of course, the above snippet doesn't actually compile:</p> <pre class="lang-none prettyprint-override"><code>PropertiesExample.java:35: unexpected type found : type parameter T required: class return new T(value); ^ 1 error </code></pre> <p>Am I doing this wrong, or am I simply trying to do something which can't be done?</p> <p><strong>Edit:</strong> Usage example:</p> <pre class="lang-java prettyprint-override"><code>// I'm trying to simplify this... protected void func1() { foobar = new Integer(properties.getProperty("foobar", "210")); foobaz = new Boolean(properties.getProperty("foobaz", "true")); } // ...into this... protected void func2() { foobar = getProperty("foobar", 210); foobaz = getProperty("foobaz", true); } </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.
 

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