mercredi 10 novembre 2021

Check if an object class is a subclass of another class, but with generics

There has been a lot of similar questions on Stack Overflow, but I didn't find any with generics playing a role

abstract class A<T> {
    public abstract T getT();
    public void someMethod(Object value){
        if(A.class.isAssignableFrom(value.getClass())
            // either B or C work, as expected
        if(A<Long>.isAssignableFrom(value.getClass()) // does not compile
            // this should allow classes like B only
    }
}
class B extends A<Long>{
    long id;
    @Override
    public Long getT(){return id;}
}
class C extends A<Integer>{
    int id;
    @Override
    public Integer getT(){return id;}
}

What I need is a way to distinguish between B and C when using some method, as shown in the second if





Aucun commentaire:

Enregistrer un commentaire