我正在Cannot refer to a non-final variable message inside an inner class defined in a different method
接受我的以下 onMessage 方法。
@Override
public void onMessage(Message msg) {
if (msg instanceof ActiveMQMessage){
try {
ActiveMQMessage aMsg = (ActiveMQMessage)msg;
String message = ""; // I cant use final here because my if else message assingment
int consumerCount =(Integer) aMsg.getProperty("consumerCount");
if(consumerCount == 0 ){
message = "No cousumers for queue bank.7083 (HNB Bank)";
}else{
message = "Added new consumer to bank.7083 (HNB Bank) total counsumers : "+consumerCount;
}
final MessageCreator request = new MessageCreator() {
public Message createMessage(final Session session) throws JMSException {
TextMessage textMessage = session.createTextMessage();
textMessage.setText(message); // I’m getting compilation issue here
return textMessage;
}
};
amqTemplate.send("HUTCH", request);
} catch (IOException e) {
e.printStackTrace();
}
}
然后我使用String [] messages = new String[1]
数组而不是我的String message
,并像下面这样更改了我的代码。
.
.
.
final String[] message = new String[1];
if(consumerCount == 0 ){
message[0] = "No cousumers for queue bank.7083 (HNB Bank)";
}else{
message[0] = "Added new consumer to bank.7083 (HNB Bank) total counsumers : "+consumerCount;
}
.
.
.
textMessage.setText(message[0]);
它编译没有任何问题。在我的理解中,消息 [0] 不是最终的。这就是为什么我能够为 message[0] 分配不同的消息。同样,尽管消息数组是最终的 setText 方法,但询问的是字符串而不是数组。我想我在这里错过了一些东西,这将阻止我理解这一点。