Reflection: cast an object to subclass without use instaceof
Posted
by Fabrizio
on Stack Overflow
See other posts from Stack Overflow
or by Fabrizio
Published on 2010-05-06T10:38:41Z
Indexed on
2010/05/06
10:58 UTC
Read the original article
Hit count: 366
I have this simple interface/class:
public abstract class Message {
}
public class Message1 extends Message{
}
public class Message2 extends Message{
}
And an utility class:
public class Utility {
public void handler(Message m){
System.out.println("Interface: Message"); }
public void handler(Message1 m){
System.out.println("Class: Message1"); }
public void handler(Message2 m){
System.out.println("Class: Message2"); }
}
Now, the main class:
public static void main(String[] args) {
Utility p=new Utility();
Message1 m1=new Message1();
p.handler(m1);
Message m=(Message) m1;
p.handler(m);
}
The output is
Class: Message1 Interface: Message
I would that p.handler(m) call the method p.handler(m:Message1)
I don't want use the "manual" command instanceof because I have many cases:
if(m instance of Message1)
p.handler((Message1)m)
else if (m instanceof Message2)
p.handler((Message2)m)
...
If I call m.getClass()
I obtain "mypackage.Message1", so the subclass and not the superclass.
I try with this code (use reflection):
p.handler(m.getClass().cast(m));
But the output is Interface: Message
So, this is my problem. I would do a runtime cast of superclass object to subclassobject without use the "code command" istanceof.
I would a right command like this:
p.handler((m.getclass)m);
How can I obtain it? It's possible?
Thank in advance.
Fabrizio
© Stack Overflow or respective owner