If you are receiving two nullable objects of Object
type and want to type-cast them dynamically to the given type by passing an in instance of Class<T>
to your method, I think you were intending to achieve this:
public static <T> Optional<T> ifNull(Object first, Object second, Class<T> type) {
return Optional.ofNullable(type.cast(first))
.or(() -> Optional.ofNullable(type.cast(second)));
}
Class<T>
object represents a class or interface
Method cast()
will cast the given object to a particular type T
, if it's the object is assignable to that type, otherwise a ClassCastException
will be thrown. Note that compiler will not issue warnings for such way of downcasting (which is always potentially unsafe).
Optional
is a special container-object introduced with Java 8 in order to be used a return type in cases when the resulting value could be null
. Optional object might either contain a value or be empty, but it would never be null
(if you are following good practices and not using optional as a field, method parameter and not storing it anywhere)
Optional.ofNullable()
creates optional object containing the given value, if it's non-null, otherwise returns an empty optional.
Method or()
will substitute the current optional object, if it is empty, with the provided optional.
The result of method execution will be the following:
Optional[first] --(first == null)--> Optional[second] --(second == null)--> empty optional
Note:
- In order to declare a generic method you have to place a generic type parameter like
<T>
or wild card <? extends Number>
between modifiers and return type or keyword void
(in the method above <T>
is ageneric type parameter and Optional<T>
is a return type).
default
is a keyword in Java.