简体   繁体   中英

Java Generics: create a general method operating on parent classes

There is the following structure

My own classes

class HERMEntityRelationshipType
class HERMEntityType extends HERMEntityRelationshipType 
class HERMRelationshipType extends HERMEntityRelationshipType

Classes generatetd from a framework.

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

I wrote two similar methods.

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

But I would like to just have one method like this:

HERMEntityRelationshipType parseERType(DBMEntityRelationshipType dbmERType){...}

But after calling that general method I am not able to cast my classes to a subclass: eg HERMEntityRelationshipType to HERMEntityType . But casting DBMDataObject to DBMEntityRelationshipType works fine. So they must implement these classes smarter then me. My cast looks like this:

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

and results in: Exception in thread "main" java.lang.ClassCastException: hermtransformation.herm.HERMEntityRelationshipType cannot be cast to hermtransformation.herm.HERMEntityType .

So what is required to cast my superclass to a subclass?

the problem here is that Java does not allow downcasting. You should create new Objects of the childclasses instead of returning new Objects of the parent class.

The parseERType Method should look something like this:

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

}

There seems to be no relation between DBMEntityRelationshipType and HERMEntityType. As per your input model, the relation between DBMDataObject and HERMEntityRelationshipType is missing. Ideally, if DBMEntityRelationshipType extends from HERMEntityRelationshipType also, then this cast would work. Moreover, you would need to cast to parent reference to project polymorphism.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM