mercredi 27 mai 2015

Bound mismatch mitigation

Say I have a generic interface:

interface SomeInterface<T> {
...
}

and two implementations:

a specific one:

class SpecificImplementation<T extends SpecificClass> implements SomeInterface<T> {
...
}

and another catch all one:

class CatchAllImplementation<T> implements SomeInterface<T> {
....
}

And I want to have a generic method similar to the following:

public <T> SomeInterface<T> getImplementation(Class<T> clazz) {
  if(SpecificClass.class.isAssignableFrom(clazz))
  {
    // do some specific stuff
    return new SpecificImplementation<T>(); // bound mismatch error here
  }
  else
  {
     // do other stuff
     return new CatchAllImplementation<T>();
  }
}

Is there any way of mitigating against the bound mismatch error? Some kind of trick to force the compiler to ignore it or similar?

I don't HAVE to bound the type parameter on the specific implementation but I would rather do so.





Aucun commentaire:

Enregistrer un commentaire