Reflection: cast an object to subclass without use instanceof

落花浮王杯 提交于 2019-12-04 11:23:18
rsp

Java will call the method on the basis of information known at compile time. What you could do is add a method to the interface that calls the correct handler method for the object.

public abstract class Message {

    public abstract void callHandler(Utility utility);

}

public class Message1 extends Message{

    public void callHandler(Utility utility) {
        utility.handler(this);
    }
}

Your calls to the handler become:

Message m=(Message) m1;
m.callHandler(p);

which now calls Utility::handler(Message1) even though the reference in main is of type of the Message interface.

I am not sure what your handle(..) methods are supposed to do, but since they depend on the specific instance of Message, you should consider adding handle() method to your Message class (as abstract method). This way, each message implements its version of handle, and you can enjoy the benefits of polymorphism:

Message m = new Message1();
m.handle();

This code will return "Class: Message1", as you need.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!