What I would like to do

In 15 years of software development I only needed this a single time. Assuming the following “architecture” :

1
2
3
interface Foo { /* ... */ }
interface Bar { /* ... */ }
class FooBar implements Foo, Bar { /* ... */ }

I would love to be able to write something like this :

1
2
3
Foo&Bar fooBar = new FooBar(); // won't compile
// or
Collection<Foo&Bar> fooBarCollection = new ArrayList<>(); // won't compile

Real world multiple bounds generics implementation

As multiple bound is allowed only on generics definition, the workaround is to create a supplier1 :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class FooBarSupplier <T extends Foo & Bar> implements Supplier<T> {

    private final T fooBar;

    public FooBarSupplier(T fooBar) {
        this.fooBar = fooBar;
    }

    @Override
    public T get() {
        return fooBar;
    }
}

Then, you should be able to do that :

1
2
3
4
FooBarSupplier<?> fooBarSupplier = new FooBarSupplier(new FooBar());

Foo foo = fooBarSupplier.get();
Bar bar = fooBarSupplier.get();

Use multiple bounds in collection

1
2
3
4
FooBar fooBar = new FooBar();

Collection<FooBarSupplier> fooBarCollection = new ArrayList<>();
fooBarCollection.add(new FooBarSupplier(fooBar));

Don’t forget to implement equals() and hashCode() methods in the supplier and make it work on the contained instance. Then, you would be able to remove elements from the collection using a different supplier instance of the same contained element :

1
fooBarCollection.remove(new FooBarSupplier(fooBar));

Casting from Object to multiple bounds

To cast an object instance into the right multiple bounds, you just have to cast into the first type in the order of declaration (Foo if Foo&Bar, Bar if Bar&Foo) :

1
2
3
4
5
6
7
Object obj = new FooBar();

// cast into Bar won't compile as it is in second position in <T extends Foo & Bar>
FooBarSupplier<?> fooBarSupplier = new FooBarSupplier((Foo) obj); 

Foo foo = fooBarSupplier.get();
Bar bar = fooBarSupplier.get();

  1. Supplier inspired by this solution ↩︎

Java