Such a construct is called an anonymous class. This is a simultaneous declaration of the inheritor of the class DefaultConsumer
, its implementation and a call to the constructor.
When you create a new object, you write:
new Foo(<parameters>);
In the case of an anonymous class, you do this:
new Foo() { // Тело нового класса }
In fact, you create a descendant of the class Foo
and at the same time call its constructor, additionally implementing / redefining the necessary methods in the body. That is, such a one-time class heir.
You can do this in a separate file:
class MyConsumer extends DefaultConsumer { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); } }
And then:
channel.basicConsume(QUEUE_NAME, true, new MyConsumer());
it would be similar in meaning, but in the future you can still create MyConsumer
objects, while using an anonymous class, you described it, created an object, and forgot about its description.
Why is it, specifically in your example? The consumer
object in this case sets the logic that should work for different actions with messages. If you look at the DefaultConsumer
source code , you will see that the handleDelivery
method handleDelivery
empty. Based on its name, it is a handler that is called if the message is delivered. In your example, for clarity, this method is redefined in a one-time inheritance class, so that the information that the message has been delivered and the message itself has been output to the console. In general, such constructions are useful, because you can make a flexible code. Today you only need to output information to the console about the delivery of the message, and tomorrow you will need to forward the message to someone, or send to grandma only after it was sent to the grandfather. Then you write some ForwardingConsumer
or GrandmaConsumer
, which will be the corresponding logic.