【问题标题】:Inheritance of model class with generic and inner classes具有泛型和内部类的模型类的继承
【发布时间】:2015-05-15 11:28:51
【问题描述】:

我希望实现该继承层次结构: GenericInsurance 扩展,其中包含内部(非静态)类 HouseInsurance

要扩展的通用类

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

类扩展泛型并具有扩展外部(封闭)类Insurance的嵌套类

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

不幸的是,当我尝试创建内部类的实例时出现错误:

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

我想我应该添加到内部类声明参数类型。但是我不知道怎么做。

通用类被许多其他类扩展并且它可以工作。这是第一次用内部类继承,所以我觉得有问题。

请帮忙。 到目前为止,我只收到编译错误。

【问题讨论】:

  • 您是如何尝试创建实例的?
  • HouseInsurance houseInsurance = Insurance.new HouseInsurance();
  • 在这种情况下 entityClass 应该指向什么?保险类还是 HouseInsurance 类??

标签: java generics model parameterized


【解决方案1】:

对于所有这些类型的场景,请查看TypeTools

public Generic() {
    entityClass = TypeResolver.resolveRawClass(Generic.class, getClass());
}

【讨论】:

  • 谢谢。我会在空闲时间测试这个解决方案
【解决方案2】:

我不确定当您创建 HouseInsurance 类的实例时,entityClass 应该引用哪个类?所以给出两种解决方案:

如果entityClass 应该指向HouseInsurance 类而不是使用此代码:

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

如果 entityClass 应该指向 Insurance 类而不是使用它:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多