-3

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();
    }
}
Issa Khodadadi
  • 917
  • 7
  • 19

2 Answers2

3

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
Tim Bish
  • 17,475
  • 4
  • 32
  • 42
1

There nothing wrong with your code, it is doing what it is meant for.

  1. Assigning message with type casting to ActiveMQObjectMessage, if it has directly or indirectly implements ObjectMessage
  2. If not caught the Exception and do proper logging so that you can inspect the source of message for correction.
  • yes you are right, thanks, as I mentioned in the previous post comment, my ptroblem was that my `message` type was not the instance of `ActiveMQObjectMessage`. – Issa Khodadadi Sep 21 '21 at 05:56