1

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: e.g.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?

0

2 Answers 2

2

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); } } 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

There shall be no relation between them. I transform them step-by-step. I need to cast HERMEntityRelationshipType -> HERMRelationshipType and HERMEntityRelationshipType -> HERMEntityType

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.