Domanda

I have a very specific problem with java generics. The follwowing classes and interfaces have been predefined:

public interface IFirst<R, T> {...}

public abstract class AbstractFirst<T extends AbstractFirst, L extends IFirst<String, T>> {...}

public interface ISecond extends IFirst<String, AbstractSecond> {...}

public abstract class AbstractSecond extends AbstractFirst<AbstractSecond, ISecond> {...}

Now I've created a following repo definition which seems to be valid:

public abstract class AbstractRepo<T extends AbstractFirst<T, IFirst<String,T>>> {...}

But now that i want to extend it:

public class RepoFirst extends AbstractRepo<AbstractSecond> {...}

I get the following error:

Bound mismatch: The type AbstractSecond is not a valid substitute for the bounded parameter 
<T extends AbstractFirst<T,IFirst<String,T>>> of the type AbstractRepo<T>

I cannot change the first four (at least not radically) beacuse they are too heavily ingrained with the rest of the application, but the second two are new and up for change if need be.

Also intrestingly it allows the following (with raw type warnings):

public class RepoFirst extends AbstractRepo {
   ...
   @Override
   AbstractFirst someAbstractMethod() {
      return new AbstractSecond() {...};
   }
   ...
}

But for code clarity I would like to implement it with clearly defining AbstractSecond as the generic type for Abstract Repo.

What am I missing?

È stato utile?

Soluzione

Your AbstractRepo expects an instance of IFirst and not a subtype of IFirst. But your AbstractSecond is clearly not IFirst. (I mean it is, from a OO standpoint but for generics, List<Number> is not the same as List<Integer>). It's ISecond. It might work if you could change your AbstractRepo from IFirst to ? extends IFirst as you did for AbstractFirst.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top