John Baum John Baum - 1 month ago 9
Java Question

Method argument that could be an implementation of N interfaces

Is there a way in Java using generics that will allow me to specify a method argument that either implements interface A OR B?

public void foo(Object bar) // bar could either be an implementation of interface A or interface B but nothing else.

private interface A<T>
{
Object work(final Fizz fizz, final T t);
}

private interface B
{
Object work(final Fizz fizz);
}

Answer

There's not a real solution in the general sense, but for your particular example, you could try something like:

public <T> void foo(A<T> bar) {
    return;
}

private interface A<T> {
    Object work(final Fizz fizz, final T t);
}

private interface B extends A<Void> {

    default Object work(final Fizz fizz) {
        return work(fizz, null);
    }

    Object work(final Fizz fizz, final Void ignoreMe);
}