0

This question is a follow up from Java Generics Wildcarding With Multiple Classes.

I'm writing an interface like this:

public interface SomeInterface {
  public Class<? extends SomeClass implements OtherInterface> getClassForObject(Object object);
}

I know that this is wrong syntax, as is Class<? extends SomeClass & OtherInterface>, and it seems all options.

I can't have the interface do what was suggested in the answer to the question linked above (public interface SomeInterface<T extends SomeClass & OtherInterface>) because implementations of this interface might want to return different things for different inputs.

I also can't create an abstract class that extends SomeClass and implements OtherInterface and have everything extend from that because there are many existing implementations of SomeClass that clients may want to extend from.

Is there any way to force implementations of this interface to return a type that fits both constraints? Besides throwing a runtime exception somewhere else in the code?

Community
  • 1
  • 1
ghopper
  • 100
  • 8

1 Answers1

1

You cannot impose multiple restrictions on a wildcard. You can declare a generic type parameter on the method instead of the interface itself, and you can impose multiple restrictions on it. Try:

public interface SomeInterface {
   public <T extends SomeClass & OtherInterface> Class<T>
      getClassForObject(Object object);
}
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • This doesn't solve the problem of clients being able to return different classes depending on the value of object. – ghopper Aug 02 '14 at 00:49