dynamic down-casting in Java
Oct. 12th, 2006 05:15 amI just ran into problems because of Java's static (non pun intended) typing. Say we have 3 classes:
We have an object named
When
* inside
* inside
* inside
This is indeed what happens if the
If they are static, however, Java will insist on calling the
Therefore, we need to down-cast. For example:
But this is bad, since it would require me to create a case for each and every subclass of
The code I really want is something like:
A extends B extends CWe have an object named
instance whose class is A.When
instance.inputMatcher(x,y) gets called, we would expect the Java dispatcher to look for the implementation of inputMatcher in this order:* inside
A* inside
B* inside
CThis is indeed what happens if the
inputMatcher methods are non-static.If they are static, however, Java will insist on calling the
inputMatcher() from C, because that is the declared type of instance.Therefore, we need to down-cast. For example:
if (matcherInstance.getClass().equals("A"))
result = ((A) instance).inputMatcher(x,y);
But this is bad, since it would require me to create a case for each and every subclass of
C, in which I down-cast instance to that type.The code I really want is something like:
result = downcast(instance, instance.getClass()).inputMatcher(a,b);