Java returns objects based on generics

I want to write a public method that passes in two objects of the same type an and b, and returns b

if an is null
public static ifObj(Object a, Object b) {
    if(null == a) {
        return b;
    }else {
        return a;
    }
}

Obj obj = ifObj(xxx, new xxx());

but the result of doing so will have to be transformed. I want to modify it on the basis of ifObj. Call the method to pass an object type or generic type, and judge that an is null, and return an object based on the type or generic generic type. Is this all right? how should the syntax be written to achieve it?

Mar.20,2021

@ learnmeahaskell gives you ideas in the comments, but I'd like to mention one more point:

ifObj (xxx, new xxx ()) , that is, whether xxx is empty or not, new xxx () will be executed to generate a new instance, which is not very good and will result in meaningless resource overhead. You can use an interface to delay loading.

public interface Supplier<T> {
    T supply();
}

public static <T> T ifObj(T a, Supplier<T> s) {
    return a == null ? s.supply() : a;
}

Obj obj = ifObj(xxx, new Supplier<Obj>() {
    @Override
    public Obj supply() {
        return new xxx();
    }
});

//  jdk8  `Optional`
Obj obj = Optional.ofNullable(xxx).orElseGet(() -> new xxx());

orElseGet is actually supplier .

Menu