Overview

In this article, we will take a look at NoSuchFieldError in Java, what is it, why it arises and how to prevent and fix it.

NoSuchFieldError in java

java.lang.NoSuchFieldError in java is caused when the Java Virtual Machine (JVM) cannot find a field (or variable) that it’s looking for.
NoSuchFieldError extends IncompatibleClassChangeError, which is thrown due to incompatible class changes.
This, in turn, indirectly extends Error, which means that your application should not try to catch or declare to throw.

There are a few reasons that can cause a NoSuchFieldError.
The most common cause is when you try to access a field that doesn’t exist. For example, if you try to access a field that’s been renamed or deleted.
Another common cause is when you try to access a field that’s private or protected. Remember, you can only access public fields from outside of the class.

NoSuchFieldError can be caught by the compiler but it can also occur at execution time when trying to access a field that does not exist.

Java docs of NoSuchFieldError state,

Thrown if an application tries to access or modify a specified field of an object, and that object no longer has that field.

Scenario

Suppose there is a class with some field as shown below

public class Employee {
   public int id;

  // other fields
}

Let’s say there is another class which accesses this field

public class EmployeeDetail {
  public void printEmployeeId() {
    Employee e = new Employee();
    System.out.println(e.id);
  }

  public static void main(String[] a) {
    EmployeeDetail ed = new EmployeeDetail();
    ed.printEmployeeId();
  }
}

Compile both classes using javac and run EmployeeDetail with java command.

There will be no problem.

Now, change the id field of Employee class to empId as below

public class Employee { 
  public int empId; 

  // other fields 
}

Now, compile Employee and without compiling EmployeeDetail, run it using java again.

You will get

Exception in thread “main” java.lang.NoSuchFieldError: id
at EmployeeDetail.printEmployeeId(EmployeeDetail.java:4)
at EmployeeDetail.main(EmployeeDetail.java:9)

Fix NoSuchFieldError

Now that we know what can cause a NoSuchFieldError, let’s talk about how to fix it.
1. If you’re getting this error because you’re trying to access a field that doesn’t exist, the fix is simple: you need to update your code to reference the new field name.
2. You need to ensure that the class used at the time of compilation is the same as the class referred at execution time.
3. If the application uses external jars, then check if the jars at compilation and execution are the same.
4. If the class that is causing NoSuchFieldError is inside an external jar, then find the version of jar that contains the missing field.
5. It might also happen that the field name is modified in the new version. In that case, update your code to refer to the modified field.

That is all on NoSuchFieldError in java.
Hope the article was useful.