Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java = What are alternatives / solutions to downcasting?

Tags:

java

I have Value-Objects/Beans (only containing members, no logic):

public class Parent {
String first;
String second;
}

Some processing logic returns the "Parent". I then do some further processing and want to add furtehr fields:

public class ParentAddedMembers extends Parent {
String third;
String fourth;
} 

The Problem is, I can NOT downcast from Parent to ParentAddedMembers.

ParentAddedMembers parentAddedMembers = (ParentAddedMembers) parent;

This seems to be invalid.

(From my point of view in this case it would be legal, when downcasting the unassigned, new fields would simply hold nulls. But it seems java does not allow this).

What is the correct solution, if I do not want to copy all fields manually (I could write a copy method that copies the Parent members to a newly created ParentAddedMembers. But this does not work for private fields. Furthermore it will break very easyly if I add/delete membes in parent...)

What is the corret solution for this?

Thanks very much!

Markus

Update: What I want to achive is. I have a thirdparty Library that returns some Objects Parent (from a search result), but I need to add further fields (metadata) to it. Downcasting, as described would solve the problem easily but does not work. I also can not change the parent as it is from a third party lib.

like image 457
Markus Avatar asked Oct 18 '25 14:10

Markus


1 Answers

(From my point of view in this case it would be legal, when downcasting the unassigned, new fields would simply hold nulls. But it seems java does not allow this).

This only makes sense intuitively because the fields in Parent and ParentAddedMembers have the same names for the fields. You say yourself that having a copy constructor is error prone due to modifications to the fields. Wouldn't such casting capabilities be too? (What if you change Parent.first to Parent.param1.)

Bottom line is that Java disallows this, because it doesn't make sense in other cases. You can't cast a Vehicle into a Car. (The Vehicle object may be a Bike.)

What is the corret solution for this?

  • One option would be to simply do

    public class Parent {
        String first;
        String second;
    
        boolean extended;
        String third;
        String fourth;
    }
    
  • or, to go the route you explain and do a copy constructor.

  • You could also solve it using reflection. Then you would be able to loop through all fields of Parent and assign the fields of ParentAddedMembers based on the field names. (But using reflection indicates some code smell actually.)

like image 54
aioobe Avatar answered Oct 20 '25 02:10

aioobe