开发者

Java generics - use same wildcard multiple times

I have a class declaration which uses generics and bounded wildcards:

class Factory<T extends Logic<? extends Entity>, 
              U extends DAO<? extends Entity>> 
{
}

Basically its a generic factory, which takes a logic interface (T) and returns a configured implementation. In order to instantiate the logic, I take a appropriate DAO class implementing the DAO interface (U).

Both interfaces for logic and DAO are generic as well and take the type of the entity to work with as their type parameter. However, I want to constrain that further, so that DAO and Logic not only have a type parameter which extends Entity, but that they extend the same Entity. The result may look similiar to that:

class <X extends Entity> Factory<T extends Logic<X>, 
              U extends DAO<X>> 
{
}开发者_StackOverflow

Can I achieve that with java generics?


Yes, you're close. Do it like this:

class Factory<X extends Entity,
              T extends Logic<X>, 
              U extends DAO<X>> 
{
}

Alternative

class Factory<T extends Logic<?>, 
              U extends DAO<?>> 
{
    // Here, the generic method parameter only requires X
    // to be the same bound at method invocation. However,
    // you will "lose" that information again when the 
    // Factory is returned.
    public static <X extends Entity,
                   T extends Logic<X>, 
                   U extends DAO<X>> Factory<T, U> createFactory(T logic, U dao)
    {
        return new Factory<T, U>(logic, dao);
    }
}


Another approach could be to provide a wrapper (although that's not really elegant ;) ):

class Entity{}

interface Logic<T extends Entity> {}

interface DAO<T extends Entity> {}

interface DaoLogic<X extends Entity> {
  DAO<X> getDAO();
  Logic<X> getLogic();
}

class Factory<T extends DaoLogic<? extends Entity>> {}


Would the following work. X would be the "common" type, where Logic and DAO both would use this type.

public class Factory<X extends Entity, T extends Logic<X>, U extends DAO<X>>
{
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜