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

  • Legacy Code Refactoring: Tips, Steps, and Best Practices
  • NullPointerException in Java: Causes and Ways to Avoid It
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • How to Activate New User Accounts by Email

Trending

  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  • System Coexistence: Bridging Legacy and Modern Architecture
  • Start Coding With Google Cloud Workstations
  1. DZone
  2. Coding
  3. Frameworks
  4. NoClassDefFoundError When Using Lambda Instead of Anonymous Class [Snippets]

NoClassDefFoundError When Using Lambda Instead of Anonymous Class [Snippets]

While it is often recommended to use lambda instead of the anonymous class in Java, the NoClassDefFoundError is becoming a problem for some. Here's how to solve it.

By 
Yanming Zhou user avatar
Yanming Zhou
·
Aug. 06, 18 · Code Snippet
Likes (4)
Comment
Save
Tweet
Share
12.5K Views

Join the DZone community and get the full member experience.

Join For Free

It's recommended to use Lambda instead of the anonymous class, but there are some pitfalls, such as the potential  NoClassDefFoundError.

In this post, I will explore this error and how to avoid it. I have two classes, RequiredObject and OptionalObject. The latter one is optional at runtime, and optional dependency is common especially for this framework.

public class RequiredObject {

    public void doSomethingElse() {
        System.out.println("doSomethingElse() called");
    }

    public void doSomething() {
        boolean optionalPresent = false;
        try {
            Class.forName("test.OptionalObject");
            optionalPresent = true;
        } catch (ClassNotFoundException e) {

        }
        OptionalObject optional = optionalPresent ? new OptionalObject() : null;
        Runnable runnable = () - > {
            if (optional != null)
                optional.doSomething();
            System.out.println("doSomething() called");
        };
        runnable.run();
    }

}
public class OptionalObject {

    public void doSomething() {
        System.out.println("I am optional");
    }

}
import org.junit.Test;

public class Tests {

    @Test
    public void methodCallWithoutNoClassDefFoundError() {
        RequiredObject required = new RequiredObject();
        required.doSomethingElse();
    }

    @Test // (expected = NoClassDefFoundError.class)
    public void methodCallWithNoClassDefFoundError() {
        RequiredObject required = new RequiredObject();
        required.doSomething();
    }

    @Test
    public void reflectWithoutNoClassDefFoundError() {
        RequiredObject.class.getMethods();
    }

    @Test // (expected = NoClassDefFoundError.class)
    public void reflectWithNoClassDefFoundError() {
        RequiredObject.class.getDeclaredMethods();
    }

}


Tests that failed were caused by the NoClassDefFoundError. This is because the compiler addes a synthetic method  private static void RequiredObject.lambda$0(OptionalObject) . It captures the OptionalObject as the parameter type, and call or get via reflection will trigger the NoClassDefFoundError. It's remarkable that Spring will call the getDeclaredMethods   on bean classes.

There is a workaround — you can use the upcase OptionalObject to Object outside lambda and downcast it inside lambda.

Object optional = optionalPresent ? new OptionalObject() : null;
Runnable runnable = () - > {
    if (optional != null)
        ((OptionalObject) optional).doSomething();
    System.out.println("doSomething() called");
};
runnable.run();
Spring Framework IT Framework POST (HTTP) Testing Dependency Workaround Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Legacy Code Refactoring: Tips, Steps, and Best Practices
  • NullPointerException in Java: Causes and Ways to Avoid It
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • How to Activate New User Accounts by Email

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!