Search code examples
javaactivemq-classicmessagemessagebroker

ClassCastException while casting activemqObjectMessage


why I can't cast ActiveMQObjectMessage in this code?

public void onMessage(Message message) {
    try {
        ActiveMQObjectMessage mqObjectMessage = (ActiveMQObjectMessage)  message; //i got exception here

        distributor.sendMessage(mqObjectMessage);

    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}

Solution

  • If the incoming type is of type TextMessage then of course you cannot cast it to an ObjectMessage as that is not the correct type as TextMessage does not implement the ObjectMessage interface. You need to use type checks to determine what type of message you are dealing with and perform the correct casts.

    if (message instanceof ObjectMessage) {
    } else if message instanceof TextMessage) {
    } // etc