NoSuchFieldError Java

Solution 1:

This error is typically thrown if you only partially recompile your code. You've got old code that is referencing a field that no longer exists in the recompiled class files.

The solution is to clean out all the class files and compile everything from fresh.

Update: If you still get the same error after recompiling everything, then you're probably compiling against one version of an external library and using another at runtime.

What you need to do now is first identify the class that is causing the problem (it looks like you have done this already) and then run your application with the -verbose:class command line option. It will dump a lot of class loading information on your standard out and you'll be able to find out where the problematic class is exactly loaded from.

Solution 2:

When the compiler compiled the code that is throwing the error, there was some other class with a field, and your class could access this field (either reading or changing the value).

On runtime, the other class somehow has no field with this name, which results in the mentioned error.

One reason might be that the second class changed without the first one being recompiled. Recompile all your classes, and you should either get a compiler error (which will give you more information on how to solve this), or the class will reference the right class.

Another reason could be that you have some class in more than one jar file (or directory) in the class path (in different versions), resulting in some other class using the wrong one. Check all your jars on duplicate classes.

Solution 3:

Something to be careful of when tracing these errors in an IDE (Eclipse in my case) is to watch the dependencies of projects your project may depend on. If you use different versions of a library in different dependent projects, the classpath loader may pick up the wrong one. This includes having a project dependent on a jar created from an Eclipse project, and having another project dependent on that project and the project which the jar was generated from. The outdated classes in the jar could potentially be loaded instead of the the classes from the project.

Example:

project1 depends on project2 and project3

project3 depends on project2.jar, a jar generated from the class files in project2

A final static field is added to a class in project2, which is recompiled, while project2.jar is not rebuilt

Running project1 may cause the exception, as the classes from project2 may be loaded from the project directly OR the jar, which doesn't have the field