You could try to pass in a default value explicitly:
public <T> T valueOrDefault(T input, T fallback) {
return input == null? fallback : input;
}
which can be used like:
String query = valueOrDefault(getParameter("query"), "");
if (query.length() == 0) {
...
}
The problem with Java generics (as opposed to, for example, C#) is, that there is no type information retained after compilation, which would allow something like new T()
to work. As an alternative approach (as was proposed in the comments to your question), you might pass in the class token:
public <T> T valueOrDefault(Class<T> token, T value) {
if (value != null) return value;
else {
final Constructor<T> ctor = token.getConstructor();
return ctor.newInstance();
}
}
(error checking omitted for brevity; code not tested, might not even compile...) This approach is pretty brittle, though.
- What if
T
does not have a default constructor?
- What if the default constructor does non-trivial stuff?
- What if a value isn't really usable after construction with the default constructor (because additional initialisations are required)?