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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

  • Carry the Bag of Reality Into the New Year? What Would Gödel Say?
  • The Self-Hosting Math Changed While We Were Still Arguing About Sovereignty
  • Beyond @Transactional: Solving the Dual-Write Problem in Distributed Microservices
  • Debugging senro Pipelines: Replay a Run, Shell Into a Live Step, Audit a Cache

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Aug. 06, 18 · Code Snippet
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
13.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook