I have classes hierarchy such as
ChildA extends Parent
ChildB extends Parent
ChildC extends Parent
then in my application, I get in a method any of this child by Parent reference.
The problem is all of these children have the same methods but their parent doesn't
So, ChildA, ChildB, and ChildC
all have getSomeValue()
getter but Parent
doesn't.
Now I need to parse the value from any of this child, but Parent reference doesn't provide me with API so I need to cast Parent to specific children type.
Below is the snippet representing what I am trying to do:
private void processChildren(Parent parent) {
ChildA childA = null;
ChildB childB = null;
ChildC childC = null;
if (parent instanceof ChildA) {
childA = parent;
}
if (parent instanceof ChildB) {
childB = parent;
}
if (parent instanceof ChildC) {
childC = parent;
}
String someValue;
if (Objects.nonNull(childA)) {
someValue = childA.getSomeValue();
} // and the same checks and extracts for each of childs and for many methods
}
As you can see in order to extract just one value I need to create 3 references, then check them in order to cast to specific type and then check what the type actually was created in order to call the method.
The question is how to properly cast the reference to the specific child reference in runtime? I guess it is possible to write using reflection, although I was not able to solve it even with reflection.
Also, even if it possible - is it ok to do that?
FYI: I am working on a legacy application so I can't change the previously written code so I can't add this API in Parent class. Also, the classes are provided from an external jar.