0

Possible Duplicate:
Calling constructor of a generic type

I want to write a method to check null for a value of anytype and return the value of the same type accordingly. How can i write it in a generic way so that i can pass any parameter and return the same if it is not null or a new object of the same type?

Something like this will be helpful, but obviously the below wont work:

public T getValue(T param) {
    if (null != param) {
        return param;
    } else {
        return ""; // or return new T
    }
}
Community
  • 1
  • 1
popcoder
  • 2,552
  • 6
  • 30
  • 45
  • This question has been asked before many times.... http://stackoverflow.com/questions/6916346/how-can-i-instantiate-a-generic-type-in-java, http://stackoverflow.com/questions/3187109/instance-of-type-generic – Lukas Eder Jul 22 '12 at 12:21
  • 1
    And in each case, the answer is "you can't really, unless you're both willing to pass around the `Class` object, and you're willing to accept the fragility of that approach." – Louis Wasserman Jul 22 '12 at 12:26
  • @LouisWasserman: Can you please explain it a bit? What do you mean by pass around the class object? – popcoder Jul 22 '12 at 12:47

1 Answers1

2

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.

  1. What if T does not have a default constructor?
  2. What if the default constructor does non-trivial stuff?
  3. What if a value isn't really usable after construction with the default constructor (because additional initialisations are required)?
Dirk
  • 29,274
  • 6
  • 76
  • 99