I'm having problem in replacing this particular example:
Consumer consumer = new DefaultConsumer(channel) {
@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 + "'");
}
};
Is it possible to replace that with lambda as it uses non-default constructor for DefaultConsumer?
It's from rabbitMQ java tutorial -> LINK to whole class
No you can't. DefaultConsumer is not a FunctionalInterface (and can't be: more info here) hence is not a lambda target.
Explanation:
The answer is no. You can create an anonymous class for non-final classes and interfaces. Is not the same for lambda expressions. These can be only used where a SAM interface is expected, i.e. interfaces with only a Single Abstract Method (before Java 8 every interface method was abstract but since Java 8 interfaces can also have default and static methods which aren't abstract because they have implementation).
Only anonymous classes which are implementations of a SAM interface (like Runnable, ActionListener, Comparator, Predicate) can be replaced by a lambda expression. DefaultConsumer cannot be a lambda target because is not even an Interface.
Even though Consumer is an Interface, it is not a SAM Interface because it has more than 1 abstract method so it can't be a lambda target either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With