I got a ClassNotFoundException or NoClassDefFoundError. How can I fix it?

Apache NetBeans Wiki Index

Note: These pages are being reviewed.

The most likely explanation is that you have a problem in your dependencies. In order for a class in one module to reference a class/interface defined in another module, the following must be true:

  1. The class/interface being referenced must be visible to the code using it, according to the normal Java visibility rules. This typically means that the class must be public, since package-private access across modules is impossible.

  2. The package containing the class/interface must be exported (marked as providing an API visible to other modules). To "export" package, right click project, select Properties → API Versioning and choose either public or friend export type.

  3. The module containing the code which uses this class/interface must declare a dependency on the module which provides it.

These rules are pretty straightforward and it is easy in most cases to verify that dependencies are set up correctly. If you receive a ClassNotFoundException or NoClassDefFoundError at runtime, the stack trace will generally lead you to the problem.

However, there are some cases where you will receive a ClassNotFoundException or NoClassDefFoundError at runtime, but finding which modules need to declare dependencies on one another is more difficult because the stacktrace does not directly identify the code involved. This occurs most frequently when you have library modules (composed of JAR files which were compiled outside of the platform). Although the dependencies were satisfied (by setting the classpath as needed) when the libraries were compiled, the developer may not have correctly set these dependencies in the platform application which uses them.

In this case, you can often locate the problem by rebuilding the suite and paying close attention to the output generated by the verify-class-linkage task. For example:

verify-class-linkage: Warning: a.SomeImplementation cannot access b.publicapi.SomeInterface

This tells us that the module which provides SomeImplementation needs to declare a dependency on the module which provides SomeInterface.

For more background, see link:.