开发者

Is it possible to introduce genericity in genericity?

Sorry for the tile... i didn't know how to resume my question.

Let me introduce my problem:

I want to get the Type of a Generic Type.

Some code:

public class AbstractDao&l开发者_JS百科t;T, PK extends Serializable> {
    public T getByPrimaryKey(PK primariKey) {
    return null;
    }
}

public class AbstractEntity<PK extends Serializable> {
    PK id;
    //Getter Setter
}

public class Entity extends AbstractEntity<Long> {
}

The code I would like to change:

 public class AbstractService<T, PK extends Serializable> {
    AbstractDao<T, PK> dao;

    public T getByPrimaryKey(final PK primaryKey) {
        return dao.getByPrimaryKey(primaryKey);
    }
 }

 public class EntityService extends AbstractService<Entity, Long> {}

The idea is to remove the "PK extends Serializable" from AbstractService and get it dynamicly.

Any idea how to do that ? --> PK should stay... I don't want to use "Object" instead of "PK" in the method:

public T getByPrimaryKey(final PK primaryKey) 

Thanks for help.

Kind regards


If you don't want a generic PK type, then you could create a PrimaryKey interface as a wrapper for the actual primary key with various implementations, such as LongPrimaryKey etc. That way you could avoid the generic type.

However, if you want to be able to pass the actual type itself (e.g. Long), then I don't see a way around the generic type, which in my opinion, is well-placed where it is.


If you create a concrete instance of AbstractDao, java can determine its generic types.

(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

Will give you the runtime type of the first Generic Paramter. This isn't always available, so check with the docs and.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜