Is there a way to define a generic method that checks for null and then creates an object?

I would like to write a method that checks where the argument is null, and if it is, returns a new object of this type. it looks like this:

public static <T> T checkNull(T obj) {
    if (null == obj) return someHowCreateTheObjectWithTypeT();
    else return obj;
}

After some trying and digging, I still cannot find a way to achieve this, is this possible in java?

At first I thought about thinking. But I just cannot get an instance of the class when the object is null, and you cannot create a class without a type name T ...

Update:

I was thinking of passing the class as a parameter, but this is not the best solution, as the following answers show :)

My currunt solution is to use the defaultValue parameter:

public static <T> T checkNull(T obj, T defaultValue) {
    if (null == obj) return defaultValue;
    return obj;
}

, , ; DEFAULT_VALUE , .

+3
4

- . , . .

public static T checkNull(Object o, Class<T> c) {
  try {
    return (o == null) ? c.newInstance() : o;
  } catch (Exception e) {
    return null;
  }
}
+3

. , , . , null , T .

, Reflection, , T , .

+3

. Class<T>, . T .

+2

, . Guava , :

String foo = Objects.firstNonNull(someString, "default");

, firstNonNull NullPointerException, null.

- , Guava Supplier<T> - :

public static T firstNonNull(T first, Supplier<? extends T> defaultSupplier) {
  return first != null ? first : Preconditions.checkNotNull(defaultSupplier.get());
}

Then you can use Supplierthat creates and returns a new instance by default when and only when the first argument is null.

+1
source

Source: https://habr.com/ru/post/1773063/


All Articles