What do "symbol not found" or "unable to resolve symbol" errors mean?
P粉106711425
P粉106711425 2023-10-09 13:52:29
0
2
986

Please explain the following about "symbol not found", "cannot resolve symbol" or "symbol not found" errors (in Java):

  • What do they mean?
  • What factors can cause these problems?
  • How do programmers fix these problems?

This question is intended to provide a comprehensive Q&A on these common compilation errors in Java.

P粉106711425
P粉106711425

reply all (2)
P粉203792468

If you forgetnew, you will also get this error:

String s = String();

Compared

String s = new String();

Because a call without thenewkeyword will try to find a (native) method namedStringthat takes no arguments - and that method signature may be undefined. p>

    P粉946437474

    0. Is there any difference between these errors?

    not real. "Symbol not found", "Cannot resolve symbol" and "Symbol not found" all mean the same thing. (Different Java compilers are written by different people, and different people use different wording to express the same thing.)

    1. What does the "symbol not found" error mean?

    First of all, this is acompilation error1. This means thatthere is a problem in your Java source code,orthere is a problem with the way you compiled it.

    Your Java source code contains the following:

    • Keywords: For example,class,while, etc.
    • Text: such astrue,false,42,'X'and"Hi Mom!".
    • operator and other non-alphanumeric tokens: such as,=,{, etc.
    • Identifiers: For example,Reader,i,toString,processEquibalancedElephants, etc.
    • Comments and spaces.

    "Symbol not found" errors are related to identifiers. When compiling code, the compiler needs to figure out the meaning of each identifier in the code.

    A "symbol not found" error means that the compiler cannot perform this operation. Your code seems to be referencing something that the compiler doesn't understand.

    2. What causes a "symbol not found" error?

    As the first order, there is only one reason. The compiler looked everywhere where the identifier should be defined, but couldn't find a definition. This can be caused by a variety of reasons. Common ones include the following:

    • For general identifiers:

      • Perhaps your name is spelled incorrectly; i.e.StringBiulderinstead ofStringBuilder. Java cannot and does not attempt to compensate for misspellings or typographical errors.
      • Maybe you made a mistake; i.e.stringBuilderinstead ofStringBuilder. All Java identifiers are case-sensitive.
      • Perhaps you are using underscores incorrectly; i.e.mystringandmy_stringare different. (If you stick to Java style rules, you will largely avoid this mistake...)
      • Perhaps you are trying to use something declared "elsewhere"; i.e. in a different context than the one you implicitly told the compiler to look at. (Different classes? Different scopes? Different packages? Different code bases?)
    • For identifiers that should reference variables:

      • Maybe you forgot to declare the variable.
      • Maybe the variable declaration went out of scope when you tried to use it. (see example below)
    • For identifiers that should be method or field names:

      • Perhaps you are trying to reference an inherited method or field that is not declared in the parent/ancestor class or interface.

      • Perhaps you are trying to reference a method or field that does not exist (i.e. has not been declared) in the type you are using; for example"rope".push()2.

      • Perhaps you are trying to use a method as a field or vice versa; for example"rope".lengthorsomeArray.length().

      • Perhaps you mistakenly manipulated the array instead of the array elements; for example

        String strings[] = ... if (strings.charAt(3)) { ... } // maybe that should be 'strings[0].charAt(3)'
    • For identifiers that should be class names:

      • Maybe you forgot to import the class.

      • Maybe you used the "asterisk" import, but the class was not defined in any package you imported.

      • Maybe you forgot anewlike this:

        String s = String(); // should be 'new String()'
      • Perhaps you are trying to import or otherwise use a class that is already declared in the default package; i.e. where the class without thepackagestatement is.

        Tip: Understand the package. You should only use the default package for simple applications consisting of one class...or at least one Java source file.

    • For cases where a type or instance does not appear to have a member (such as a method or field) that you expect it to have:

      • Maybe you have declared a nested class or generic parameter,hiding the type you wantto use.
      • Maybe you are hiding static variables or instance variables.
      • Perhaps you imported the wrong type; for example because IDE completion or autocorrect might suggestjava.awt.Listinstead ofjava.util.List.
      • Perhaps you are using (compiling) the wrong version of the API.
      • Maybe you forgot to cast the object to the appropriate subclass.
      • Perhaps you havedeclared the type of the variableas the supertype of the member you are looking for.

    Questions are usually a combination of the above. For example, maybe you "star" importedjava.io.*and then tried to use theFilesclass... which was injava.nio代码> instead ofjava.io. Or maybe you plan to writeFile..., which is a class injava.io.


    The following example illustrates how incorrect variable scoping can cause a "symbol not found" error:

    List
               
                strings = ... for (int i = 0; i
                

    This will give a "symbol not found" error foriin theifstatement. Although we declarediearlier, that declaration onlyforstatement and its bodyscope. The reference toiin theifstatementcannot see the declaration ofi. Itis out of range.

    (An appropriate correction here might be to move theifstatement inside the loop, or to declareibefore the loop begins.)


    Here is a confusing example where a typo results in a seemingly inexplicable "symbol not found" error:

    for (int i = 0; i

    This will give you a compile error on theprintlncall stating thaticannot be found. But (I hear you say) I did announce it!

    The problem is the semicolon (;) before{. Java language syntax defines a semicolon in this context as anempty statement. The empty statement will then become the body of theforloop. So this code actually means:

    for (int i = 0; i

    { ... }block is not the body of theforloop, so the previous declaration inicode>for statementOut of rangein block.


    This is another example of a "symbol not found" error caused by a typo.

    int tmp = ... int res = tmp(a + b);

    Despite the previous declaration,tmpin thetmp(...)expression is incorrect. The compiler looks for a method namedtmpbut cannot find it. Thetmpdeclared earlier is in the variable's namespace, not the method's namespace.

    In the examples I encountered, the programmer actually left out an operator. What he originally wanted to write was this:

    int res = tmp * (a + b);

    There is another reason why the compiler may not be able to find a symbol if compiling from the command line. You may have simply forgotten to compile or recompile some other classes. For example, if you have classesFooandBar, whereFoousesBar. If you have never compiledBarand runjavac Foo.java, you can easily find that the compiler cannot find the symbolBar. The simple answer is to compileFooandBartogether; for examplejavac Foo.java Bar.javaorjavac *.java. Or better still use Java build tools; such as Ant, Maven, Gradle, etc.

    There are some other, more obscure reasons... which I'll discuss below.

    3. How to fix these errors?

    Generally speaking, you first need to find outthe cause of thecompilation error.

    • Look at the line in the file indicated by the compilation error message.
    • Determine which symbol the error message is talking about.
    • Find outwhythe compiler says it cannot find the symbol; see above!

    Then youthink aboutwhat your code should say. Finally, you determine what corrections need to be made to the source code to accomplish what you want.

    Please note that not every "correction" is correct. think about it:

    for (int i = 1; i

    Suppose the compiler prompts "symbol not found" forj. There are a number of ways I can "fix" this:

    • I could change the innerfortofor (int j = 1; j - which might be correct.
    • I could add a forjstatement inside theforloop or outside theforloopbefore- that might be correct.
    • I can changejtoiinside the innerforloop - probably wrong!
    • etc.

    The point is, youneed tounderstand what your code is trying to do in order to find the correct fix.

    4. unknown reason

    In the following few cases, "symbol not found" may seem puzzling... until you look closer.

    1. Incorrect Dependencies: If you are using an IDE or build tool that manages build paths and project dependencies, you may have made a mistake with a dependency; for example, omitting dependencies, or the wrong version was selected. If you use a build tool (Ant, Maven, Gradle, etc.), check your project's build files. If you are using an IDE, check your project's build path configuration.

    2. Symbol 'var' not found: You may be trying to use an older version to compile source code that uses local variable type inference (i.e.vardeclarations) Compiler or older--sourcelevel.varwas introduced in Java 10. Check your JDK version and build files, and (if this happens in an IDE) IDE settings.

    3. You didn't compile/recompile: Sometimes new Java programmers don't understand how the Java toolchain works, or don't implement a repeatable "build process"; e.g. using an IDE, Ant, Maven, Gradle, etc. In this case, the programmer may end up chasing down a phantom error that was actually caused by, for example, not recompiling the code correctly.

      Another example is when you compile and run a class using (Java 9)java SomeClass.java. If the class depends on another class that you haven't compiled (or recompiled), you may get an "unable to resolve symbol" error involving the second class. Other source files are not automatically compiled. The new "Compile and Run" mode of thejavacommand is not suitable for running programs with multiple source code files.

    4. Early Build Issue: Early builds may fail, resulting in JAR files missing classes. If you use build tools, you'll usually notice such failures. However, if you obtain JAR files from someone else, you rely on them building correctly and noticing errors. If you suspect this, usetar -tvfto list the contents of the suspect JAR file.

    5. IDE Issue: People have reported situations where their IDE gets confused and the compiler in the IDE cannot find a class that exists... or vice versa.

      • This may occur if the IDE is configured with the wrong JDK version.

      • This can happen if the IDE's cache is out of sync with the file system. There are some IDE specific ways to solve this problem.

      • This may be an IDE error. For example, @Joel Costigliola describes a scenario where Eclipse fails to handle the Maven "test" tree correctly:See this answer. (Apparently this particular bug was fixed long ago.)

    6. Android Issue: When you program for Android, if you encounter a "symbol not found" error related toR, please note thatRSymbols are defined by thecontext.xmlfile. Check that yourcontext.xmlfile is correct and in the correct location, and that the correspondingRclass file has been generated/compiled. Note that Java symbols are case-sensitive, so the corresponding XML ids are also case-sensitive.

      Other symbol errors on Android may be due to the reasons mentioned previously; such as missing or incorrect dependencies, incorrect package names, methods or fields that do not exist in a specific API version, spelling/typing errors etc.

    7. Hidden System Classes: I have seen cases where the compiler complained thatsubstringwas an unknown symbol, as shown below

      String s = ... String s1 = s.substring(1);

      It turns out that the programmer created their own version ofString, and his version of the class did not define thesubstringmethod. I've seen people useSystem,Scanner, and other classes to do this.

      Lesson:Do not define your own class with the same name as a public library class!

      This problem can also be solved by using a fully qualified name. For example, in the example above, the programmercouldwrite:

      java.lang.String s = ... java.lang.String s1 = s.substring(1);
    8. Homographs:If you use UTF-8 encoding for your source files, you may end up with identifiers thatlookthe same but are actually different because they contain homographs Word. Please seethis pagefor more information.

      You can avoid this by limiting yourself to ASCII or Latin-1 as the source file encoding, and using Java\uxxxxto escape other characters.


    1 - If youdosee this in a runtime exception or error message, you have configured your IDE to run code with compilation errors, or your app The program is generating and compiling code at runtime.
    2 - Three basic principles of civil engineering: water does not flow to higher places, boards become stronger as they face each other, andyou cannot push the rope.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!