Search code examples
javagenericsmodelparameterized

Inheritance of model class with generic and inner classes


I would like to have implemented that inheritance hierarchy: Generic is extended by Insurance which contains inner (non static) class HouseInsurance

Generic class to be extended

public abstract class Generic<T extends Generic> {
    public Generic() {
       entityClass = ((Class) ((Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]));
    }
}

Class that extends generic and has nested class that extends Outer (enclosing) class Insurance

public class Insurance extends Generic<Insurance> {
   public class HouseInsurance extends Insurance {
   }
}

Unfortunately when I am trying to create instance of inner class I am getting an error:

ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

I suppose that I should add to inner class declaration parameter type. But I do not know how.

Generic class is extended by many other classes and it works. This is the first inheritance with inner class, so I think that there is a problem.

Please help. So far I am getting only compilation error.


Solution

  • I am not sure that when you create instance of HouseInsurance class which class should entityClass refer to? So giving both solutions:

    If entityClass should point to HouseInsurance class than use this code:

    public Generic() {
        Type genericType = getClass().getGenericSuperclass();
        if (genericType instanceof ParameterizedType) {
            entityClass = ((Class) ((Class) ((ParameterizedType) genericType).getActualTypeArguments()[0]));
        }
        else {
            entityClass = getClass().getSuperclass();
        }
    }
    

    And if entityClass should point to Insurance class than use this instead:

    public Generic() {
        Class cClass = getClass();
        do {
            Type genericType = cClass.getGenericSuperclass();
    
            if (genericType instanceof ParameterizedType) {
                entityClass = ((Class) ((Class) ((ParameterizedType) genericType).getActualTypeArguments()[0]));
            }
            else {
                cClass = cClass.getSuperclass();
            }
        } while (entityClass == null);
    }