I\'ve added a human-readable configuration file to my app using java.util.Properties and am trying to add a wrapper around it to make type conversions easier. Specifically,
Generics are implemented using type erasure in Java. In English terms, most generic information are lost at compile time, and you can't know the actual value of T at runtime. This means you simply can't instanciate generic types.
An alternate solution is to provide your class with the type at runtime:
class Test {
Class klass;
Test(Class klass) {
this.klass = klass;
}
public void test() {
klass.newInstance(); // With proper error handling
}
}
Edit: New example closer to your case
static T getProperty(String key, T fallback, Class klass) {
// ...
if (value == null) {
return fallback;
}
return (T) klass.newInstance(); // With proper error handling
}