Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8298065

Provide more information in message of NoSuchFieldError

XMLWordPrintable

    • b05
    • generic
    • generic

      A DESCRIPTION OF THE PROBLEM :
      A java.lang.NoSuchFieldError is typically thrown when you remove a field but do not recompile the client code that calls the field. However, the message does not indicate in which class the field was not found.

      Additionally, java.lang.NoSuchFieldError is thrown if the field is still present but the types are incompatible. For example, if a field is first defined as int, and later changed to long without recompiling the client.
      Example:

      ```
      $ echo 'public class Main {
        public static void main(String[] args) {
          Object x = Other.x;
          System.out.println("x = " + x);
        }
      }' > Main.java

      $ echo 'public class Other {
        public static int x = 123;
      }' > Other.java

      $ javac Main.java Other.java

      $ java Main
      x = 123

      $ sed -e 's/int/long/' -i Other.java

      $ cat Other.java
      public class Other {
        public static long x = 123;
      }

      $ javac Other.java

      $ java Main
      Exception in thread "main" java.lang.NoSuchFieldError: x
              at Main.main(Main.java:3)
      ```

      In this case the error message is even misleading, because there is indeed a field with this name, only the types are not compatible.

      Suggestion: The message of NoSuchFieldError should contain more information/context, for example the involved class and, if applicable, a hint about type incompatibility
      In this case something like "class Other misses field 'int x'" would be more helpful than just "x".


            matsaave Matias Saavedra Silva
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            8 Start watching this issue

              Created:
              Updated:
              Resolved: