Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: replace anonymous class with lambda

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

like image 419
ohwelppp Avatar asked Nov 14 '17 13:11

ohwelppp


1 Answers

No you can't. DefaultConsumer is not a FunctionalInterface (and can't be: more info here) hence is not a lambda target.

Explanation:

Can every anonymous class be replaced by a lambda expression?

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).

So which anonymous classes can be replaced with a lambda expression?

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.

And what about Consumer?

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.

like image 181
Juan Carlos Mendoza Avatar answered Oct 03 '22 07:10

Juan Carlos Mendoza