简体   繁体   中英

generic interface with bounded generic interface

Say I have generics interface :

public interface MyContainer<E>{
     E someMethod();
}

Now I have another interface that I want it to be something like this:

public interface MyService<T extends MyContainer<E>>{
     // someMethod goes here   
}

It doesn't compile of course, it only compiles like this :

public interface MyService<E,T extends MyContainer<E>>{
     // someMethod goes here   
}

but I don't like it since MyService interface doesn't care about E it only cares that its type parameter extends MyContainer. Any ideas how to solve it?

but I don't like it

Start liking it.

You must declare type parameters before referencing them, just as you would declare variables before using them.

If you care about the type of E , then you must declare it. The interface MyService does care about E if it's referencing it with T extends MyContainer<E> .

If your interface doesn't care about what E is at all, then you could use an unbounded wildcard.

public interface MyService<T extends MyContainer<?>>

However, every implementation of this interface would need to either redeclare T exactly like this or supply a type argument that satisfies this constraint exactly. You wouldn't be able to get rid of that ? .

Your declaring E and using it as you are is the best solution I can see. Having to type an extra E, is no big problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM