Java泛型:创建对父类进行操作的通用方法
有以下结构 我自己的班级Java泛型:创建对父类进行操作的通用方法,java,oop,generics,inheritance,Java,Oop,Generics,Inheritance,有以下结构 我自己的班级 class HERMEntityRelationshipType class HERMEntityType extends HERMEntityRelationshipType class HERMRelationshipType extends HERMEntityRelationshipType 类从框架生成 class DBMEntityRelationshipType extends DBMDataObject class DBMEntityType ext
class HERMEntityRelationshipType
class HERMEntityType extends HERMEntityRelationshipType
class HERMRelationshipType extends HERMEntityRelationshipType
类从框架生成
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){...}
HERMEntityType entityType = (HERMEntityType) parseERType((DBMEntityRelationshipType) dataobject);
HERMEntityRelationshipType parseERType(DBMEntityRelationshipType dbmERType){
if(dbmERType.getClass().equals(DBMEntityType.class)) {
return new HERMEntityType(dbmERType);
} else {
return new HERMRelationshipType(dbmERType);
}
}
但是在调用这个通用方法之后,我无法将我的类转换为子类:例如hermanityrelationshipType
到hermanityType
。但是将DBMDataObject
转换为dbmentyrelationshipType
效果很好。所以他们必须比我更聪明地实现这些类。我的演员阵容如下:
HERMEntityRelationshipType parseERType(DBMEntityRelationshipType dbmERType){...}
HERMEntityType entityType = (HERMEntityType) parseERType((DBMEntityRelationshipType) dataobject);
HERMEntityRelationshipType parseERType(DBMEntityRelationshipType dbmERType){
if(dbmERType.getClass().equals(DBMEntityType.class)) {
return new HERMEntityType(dbmERType);
} else {
return new HERMRelationshipType(dbmERType);
}
}
并导致:线程“main”java.lang.ClassCastException中的异常:hermtransformation.herm.hermentyRelationshipType无法转换为hermtransformation.herm.HERMEntityType
那么,将我的超类强制转换为子类需要什么呢?DBmentyRelationshipType和HermanityType之间似乎没有关系。根据您的输入模型,DBMDataObject和HermanityRelationshipType之间的关系缺失。理想情况下,如果DBmentyRelationshipType也扩展自HermentyRelationshipType,则此转换将起作用。此外,您还需要将对项目多态性的引用转换为父引用。这里的问题是Java不允许向下转换。您应该创建子类的新对象,而不是返回父类的新对象 ParserType方法应如下所示:
HERMEntityRelationshipType parseERType(DBMEntityRelationshipType dbmERType){...}
HERMEntityType entityType = (HERMEntityType) parseERType((DBMEntityRelationshipType) dataobject);
HERMEntityRelationshipType parseERType(DBMEntityRelationshipType dbmERType){
if(dbmERType.getClass().equals(DBMEntityType.class)) {
return new HERMEntityType(dbmERType);
} else {
return new HERMRelationshipType(dbmERType);
}
}
他们之间不应有任何关系。我一步一步地改变它们。我需要转换
hermanityrelationshipType
->hermanityrelationshipType
和hermanityrelationshipType
->hermanityType