Java 8: replace anonymous class with lambda

I had a problem replacing this specific 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 this with lambda, since it uses the default constructor for DefaultConsumer?

This is from the java tutorial rabbitMQ -> LINK for the whole class

+5
source share
1 answer

No, you can’t. DefaultConsumer is not a FunctionalInterface (and cannot be: more here ), therefore, is not a lambda target.

Explanation:

Is it possible to replace each anonymous class with a lambda expression?

The answer is no. You can create an anonymous class for non-final classes and interfaces. Not the same for lambda expressions. They can only be used where the SAM interface is expected, i.e. Interfaces with only one abstract method (prior to Java 8, each interface method was abstract, but since Java 8 interfaces can also have standard and static methods that are not abstract because they have an implementation).

So, what anonymous classes can be replaced with a lambda expression?

Only anonymous classes that are implementations of the SAM interface (for example, Runnable, ActionListener, Comparator, Predicate) can be replaced with a lambda expression. DefaultConsumer cannot be a lambda target because it is not even an interface.

What about the consumer?

Although Consumer is an interface, it is not a SAM interface because it contains more than one abstract method, t and a lambda target.

+6
source

Source: https://habr.com/ru/post/1273356/


All Articles