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 , .