Reputation: 11486
I have come across the following method in Spring for JMS. The class basically sends a message to ActiveMQ (my Message Queue Server) and it uses the following method:
public void sendMessage(final String message) {
this.jmsTemplate.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(message);
}
});
}
My question is what is the point of declaring the method parameter message
of type String
final?
Upvotes: 2
Views: 243
Reputation: 4092
When you instantiate the unnamed class that extends MessageCreator
, the Java compiler let you access local scope for referencing objects used outside the new unnamed class definition.
It does that by statically associating your new unnamed class with the reference of the object you mention by the variable.
Every variable that references an object/value must be final, because if you change its value dinamically like:
public void sendMessage(String message) {
this.jmsTemplate.send(new MessageCreator() {
... // some code
message = // something else
...
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(message);
}
});
}
The compiler cannot recognize that message variable has changed its referenced object, and thus you will not get expected behaviour.
Therefore, every reference in an inner unnamed class must be final (i.e. it cannot change its referenced object/value).
Upvotes: 0
Reputation: 105
I would guess it's a security measure preventing you from changing the message afterwards. If it's declared final you can only assign the String value once(when the method is called in this scenario). I'm not sure this was the answer you wanted. Add any comments if I got your question wrong.
Upvotes: 0
Reputation: 109613
In the anonymous class. child of MessageCreator message
is used, even after sendMessage returned and parameter and local variables on the stack are no longer there.
So actually a copy of the variable is made in the MessageCreator child. And the java designers thought it wise to make both variables behind the same name final; otherwise they would need some synchronisation of copying.
Hence parameters and local variables need to be final.
Upvotes: 3
Reputation: 3154
It means that the String message is not allowed to be assigned any other value inside the sendMessage method. You will get a compile time error if you do something like :
message="just test";
inside sendMessage.
Upvotes: 2