Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to deduct nested generic type

Tags:

java

generics

Suppose I have class:

public interface ObjectWithId<T> {
    T getId();

    void setId(T id);
}

public class BaseDBObject<T> implements ObjectWithId<T> {
    // Common fields:
    private T id;
    private String createdBy;
...
}

And one concrete:

public class ConstituentEntity extends BaseDBObject<Integer> {
...
}

Then I create some service, which say also take generic parameter one of ? extends BaseDBObject and in some method should operate with id of appropriate type. Now it implemented with double generics:

abstract public class BaseService<IdT,T extends BaseDBObject<IdT>> {
    public T getById(IdT id){
        return getDao().getById(id);
    }
}

public class ConstituentEntityService extends BaseService<Integer, ConstituentEntity>{
...
}

But look at last definition again. I known what ConstituentEntity already have Integer as their key holder, so it is seems ugly for me again provide that type for service.

I look some possibility to write next construction:

abstract public class BaseService<T extends BaseDBObject> {
    public T getById(??T.T?? id){
        return getDao().getById(id);
    }
}

In C++ we have typename and typedef for such cases with their complex but powerful metaprogramming possibilities. Is something similar possible in Java?

like image 291
Hubbitus Avatar asked Apr 12 '26 15:04

Hubbitus


1 Answers

I guess, it's not possible. If you have many services which use Integer as T, then you may define intermediate class:

public abstract class IntegerService<S extends BaseDBObject<Integer>> 
                                  extends BaseService<Integer, S>{
    ...
}

And use public class ConstituentEntityService extends IntegerService<ConstituentEntity>. But you will have to do this for every T type which might be inappropriate if there are many different types used as T.

like image 80
Tagir Valeev Avatar answered Apr 14 '26 04:04

Tagir Valeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!