Java Generics:创建一个在父类上运行的通用方法

时间:2015-03-17 18:04:49

标签: java oop generics inheritance

有以下结构

我自己的课程

class HERMEntityRelationshipType
class HERMEntityType extends HERMEntityRelationshipType 
class HERMRelationshipType extends HERMEntityRelationshipType

来自框架的类generatetd。

class DBMEntityRelationshipType extends DBMDataObject
class DBMEntityType extends DBMDataObject
class DBMRelationshipType extends DBMDataObject

我写了两个类似的方法。

private HERMEntityType parseERType(DBMEntityType dbmEntityType) {...}
private HERMRelationshipType parseERType(DBMRelationshipType dbmRelationshipType){...}

但我想有一个像这样的方法:

HERMEntityRelationshipType parseERType(DBMEntityRelationshipType dbmERType){...}

但在调用通用方法后,我无法将类转换为子类:例如HERMEntityRelationshipTypeHERMEntityType。但是将DBMDataObject投射到DBMEntityRelationshipType可以正常工作。所以他们必须比我更聪明地实现这些类。我的演员看起来像这样:

HERMEntityType entityType = (HERMEntityType) parseERType((DBMEntityRelationshipType) dataobject);

并导致:Exception in thread "main" java.lang.ClassCastException: hermtransformation.herm.HERMEntityRelationshipType cannot be cast to hermtransformation.herm.HERMEntityType

那么将我的超类强制转换为子类需要什么?

2 个答案:

答案 0 :(得分:2)

这里的问题是Java不允许向下转发。您应该创建子类的新对象,而不是返回父类的新对象。

parseERType方法应如下所示:

HERMEntityRelationshipType parseERType(DBMEntityRelationshipType   dbmERType){
    if(dbmERType.getClass().equals(DBMEntityType.class)) {
        return new HERMEntityType(dbmERType);
    } else {
        return new HERMRelationshipType(dbmERType);
    }

}

答案 1 :(得分:0)

DBMEntityRelationshipType和HERMEntityType之间似乎没有任何关系。根据您的输入模型,缺少DBMDataObject和HERMEntityRelationshipType之间的关系。理想情况下,如果DBMEntityRelationshipType也从HERMEntityRelationshipType扩展,那么此转换将起作用。此外,您需要转换为项目多态性的父引用。