DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Mastering Exception Handling in Java Lambda Expressions
  • JSON Handling With GSON in Java With OOP Essence
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut

Trending

  • After 9 Years, Microsoft Fulfills This Windows Feature Request
  • Introduction to Retrieval Augmented Generation (RAG)
  • Useful System Table Queries in Relational Databases
  • Memory Leak Due to Time-Taking finalize() Method
  1. DZone
  2. Coding
  3. Frameworks
  4. How Lambdas And Anonymous Inner Classes Work

How Lambdas And Anonymous Inner Classes Work

Anonymous Inner Classes and lambdas have some similarities, but their differences are important to know if you're going to use them in your work.

By 
Martin Farrell user avatar
Martin Farrell
·
Feb. 08, 17 · Tutorial
Likes (31)
Comment
Save
Tweet
Share
55.7K Views

Join the DZone community and get the full member experience.

Join For Free

At first glance, a lambda looks like a shorthand version of an anonymous inner class. But they are not. Today, we'll cover the differences between lambdas and AICs

Key Points

  • Lambdas implement a functional interface.
  • Anonymous Inner Classes can extend a class or implement an interface with any number of methods.
  • Variables – Lambdas can only access final or effectively final.
  • State – Anonymous inner classes can use instance variables and thus can have state, lambdas cannot.
  • Scope – Lambdas can't define a variable with the same name as a variable in enclosing scope.
  • Compilation – Anonymous compiles to a class, while lambda is an invokedynamic instruction.

How They Work

Anonymous Inner Classes (AICs)

  • The compiler generates a class file for each anonymous inner class.
    • For example – AnonymousInnerClass$1.class
  • Like all classes, it needs to be loaded and verified at startup.

Lambdas

The key to lambda implementation is the InvokeDynamic instruction, introduced in Java 7. This allows dynamic languages to bind to symbols at runtime.

A lambda works like this:

  • Generates invokedynamic call site and uses a lambdafactory to return the functional implementation.
  • Lambda converted to a method to be invoked by invokedynamic.
  • The method is stored in a class as a private static method.
  • There are two lambda types. Non-capturing lambdas only use fields inside their bodies, whereas capturing lambdas access fields outside their bodies.

Non-Capturing Lambdas

Doesn't access fields outside its body:

public class NonCapturingLambda {     
  public static void main(String[] args) {        
    Runnable nonCapturingLambda = () -> System.out.println("NonCapturingLambda");        
    nonCapturingLambda.run();     
  } }

If we decode the class file using the CFR decompiler, we see the:

  • LambdaMetafactory
  • Lambda is a static void method in our class
java -jar cfr_0_119.jar NonCapturingLambda --decodelambdas false 
/*  * Decompiled with CFR 0_119.  */ 
import java.io.PrintStream; 
import java.lang.invoke.LambdaMetafactory; 
public class NonCapturingLambda {     
    public static void main(String[] args) {         
        Runnable nonCapturingLambda = (Runnable)LambdaMetafactory.metafactory(null, 
           null, null, ()V, lambda$0(), ()V)();        
        nonCapturingLambda.run();     
    }     

    private static /* synthetic */ void lambda$0() 
    {         System.out.println("NonCapturingLambda");     
    } 
}

Capturing Lambdas

Accesses final or effectively final fields outside their bodies:

public class CapturingLambda {     
    public static void main(String[] args) 
    {         
        String effectivelyFinal = "effectivelyFinal";         
        Runnable capturingLambda = () -> System.out.println("capturingLambda " + effectivelyFinal);         
        capturingLambda.run();     } 
}

This decompiles to:

java -jar cfr_0_119.jar CapturingLambda --decodelambdas false 
/*  * Decompiled with CFR 0_119.  */ 
import java.io.PrintStream; 
import java.lang.invoke.LambdaMetafactory; 
public class CapturingLambda {     
    public static void main(String[] args) {        
        String effectivelyFinal = "effectivelyFinal";         
        Runnable capturingLambda = 
          (Runnable)LambdaMetafactory.metafactory(null, null, null, ()V, 
                                                  lambda$0(java.lang.String ), 
                                                  ()V)((String)effectivelyFinal); 
          capturingLambda.run();     
    }     
    private static /* synthetic */ void lambda$0(String string) {         
        System.out.println("capturingLambda " + string);     
    } 
}

The interesting part is that the lambda$0 method signature has gone from empty to taking a parameter String.

Java (programming language) Lambda architecture Object type (object-oriented programming)

Published at DZone with permission of Martin Farrell, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Exception Handling in Java Lambda Expressions
  • JSON Handling With GSON in Java With OOP Essence
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!