简体   繁体   English

“找不到符号”或“无法解析符号”错误是什么意思?

[英]What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

Please explain the following about "Cannot find symbol", "Cannot resolve symbol" or "Symbol not found" errors (in Java):请解释以下有关“无法找到符号”、“无法解析符号”或“找不到符号”的错误(在 Java 中):

  • What do they mean?他们的意思是什么?
  • What things can cause them?什么事情会导致它们?
  • How does the programmer go about fixing them?程序员 go 如何修复它们?

This question is designed to seed a comprehensive Q&A about these common compilation errors in Java.这个问题旨在为 Java 中的这些常见编译错误提供全面的问答。

0. Is there any difference between the two errors? 0.这两个错误有什么区别吗?

Not really.并不真地。 "Cannot find symbol", "Cannot resolve symbol" and "Symbol not found" all mean the same thing. “找不到符号”、“无法解析符号”和“找不到符号”都是同一个意思。 Different Java compilers use different phraseology.不同的 Java 编译器使用不同的措辞。

1. What does a "Cannot find symbol" error mean? 1. “找不到符号”错误是什么意思?

Firstly, it is a compilation error 1 .首先,这是一个编译错误1 ​​。 It means that either there is a problem in your Java source code, or there is a problem in the way that you are compiling it.这意味着要么你的 Java 源代码有问题,要么你编译它的方式有问题。

Your Java source code consists of the following things:您的 Java 源代码包含以下内容:

  • Keywords: like class , while , and so on.关键字:如classwhile等。
  • Literals: like true , false , 42 , 'X' and "Hi mum!"文字:如truefalse42'X'"Hi mum!" . .
  • Operators and other non-alphanumeric tokens: like + , = , { , and so on.运算符和其他非字母数字标记:如+={等。
  • Identifiers: like Reader , i , toString , processEquibalancedElephants , and so on.标识符:如ReaderitoStringprocessEquibalancedElephants等。
  • Comments and whitespace.注释和空格。

A "Cannot find symbol" error is about the identifiers. “找不到符号”错误与标识符有关。 When your code is compiled, the compiler needs to work out what each and every identifier in your code means.编译代码时,编译器需要弄清楚代码中每个标识符的含义。

A "Cannot find symbol" error means that the compiler cannot do this. “找不到符号”错误意味着编译器无法执行此操作。 Your code appears to be referring to something that the compiler doesn't understand.您的代码似乎指的是编译器不理解的东西。

2. What can cause a "Cannot find symbol" error? 2. 什么会导致“找不到符号”错误?

As a first order, there is only one cause.作为第一顺序,只有一个原因。 The compiler looked in all of the places where the identifier should be defined, and it couldn't find the definition.编译器查看了所有应该定义标识符的地方,但找不到定义。 This could be caused by a number of things.这可能是由多种原因造成的。 The common ones are as follows:常见的有以下几种:

  • For identifiers in general:对于一般标识符:

    • Perhaps you spelled the name incorrectly;也许你拼错了名字; ie StringBiulder instead of StringBuilder .StringBiulder而不是StringBuilder Java cannot and will not attempt to compensate for bad spelling or typing errors. Java 不能也不会尝试弥补拼写错误或输入错误。
    • Perhaps you got the case wrong;也许你搞错了; ie stringBuilder instead of StringBuilder .stringBuilder而不是StringBuilder All Java identifiers are case sensitive.所有 Java 标识符都区分大小写。
    • Perhaps you used underscores inappropriately;也许你不恰当地使用了下划线; ie mystring and my_string are different.mystringmy_string是不同的。 (If you stick to the Java style rules, you will be largely protected from this mistake ...) (如果你坚持 Java 风格的规则,你将在很大程度上避免这个错误......)
    • Perhaps you are trying to use something that was declared "somewhere else";也许您正在尝试使用被声明为“其他地方”的东西; ie in a different context to where you have implicitly told the compiler to look.即在与您隐式告诉编译器查看的不同上下文中。 (A different class? A different scope? A different package? A different code-base?) (不同的类?不同的范围?不同的包?不同的代码库?)
  • For identifiers that should refer to variables:对于应该引用变量的标识符:

    • Perhaps you forgot to declare the variable.也许你忘了声明变量。
    • Perhaps the variable declaration is out of scope at the point you tried to use it.也许变量声明在您尝试使用它时超出了范围。 (See example below) (见下面的例子)
  • For identifiers that should be method or field names:对于应该是方法或字段名称的标识符:

    • Perhaps you are trying to refer to an inherited method or field that wasn't declared in the parent / ancestor classes or interfaces.也许您正在尝试引用未在父/祖先类或接口中声明的继承方法或字段。

    • Perhaps you are trying to refer to a method or field that does not exist (ie has not been declared) in the type you are using;也许您正试图引用您正在使用的类型中不存在(即尚未声明)的方法或字段; eg "rope".push() 2 .例如"rope".push() 2

    • Perhaps you are trying to use a method as a field, or vice versa;也许您正在尝试将方法用作字段,反之亦然; eg "rope".length or someArray.length() .例如"rope".lengthsomeArray.length()

    • Perhaps you are mistakenly operating on an array rather than array element;也许您错误地对数组而不是数组元素进行了操作; eg例如

       String strings[] = ... if (strings.charAt(3)) { ... } // maybe that should be 'strings[0].charAt(3)'
  • For identifiers that should be class names:对于应该是类名的标识符:

    • Perhaps you forgot to import the class.也许您忘记了导入该类。

    • Perhaps you used "star" imports, but the class isn't defined in any of the packages that you imported.也许您使用了“星号”导入,但该类未在您导入的任何包中定义。

    • Perhaps you forgot a new as in:也许你忘记了一个new的:

       String s = String(); // should be 'new String()'
  • For cases where type or instance doesn't appear to have the member (eg method or field) you were expecting it to have:对于类型或实例似乎没有您期望的成员(例如方法或字段)的情况:

    • Perhaps you have declared a nested class or a generic parameter that shadows the type you were meaning to use.也许您已经声明了一个嵌套类或一个泛型参数,这些参数隐藏了您打算使用的类型。
    • Perhaps you are shadowing a static or instance variable.也许您正在隐藏静态或实例变量。
    • Perhaps you imported the wrong type;也许你输入了错误的类型; eg due to IDE completion or auto-correction may have suggested java.awt.List rather than java.util.List .例如,由于 IDE 完成或自动更正可能建议使用java.awt.List而不是java.util.List
    • Perhaps you are using (compiling against) the wrong version of an API.也许您正在使用(编译)错误版本的 API。
    • Perhaps you forgot to cast your object to an appropriate subclass.也许您忘记将对象转换为适当的子类。
    • Perhaps you have declared your variable's type to be a supertype of the one with the member you are looking for.也许您已经将变量的类型声明为您正在寻找的成员的超类型。

The problem is often a combination of the above.问题通常是上述问题的组合。 For example, maybe you "star" imported java.io.* and then tried to use the Files class ... which is in java.nio not java.io .例如,也许你“星”导入了java.io.* ,然后尝试使用Files类......它在java.nio而不是java.io中。 Or maybe you meant to write File ... which is a class in java.io .或者,也许您打算编写File ... 这java.io中的一个类。


Here is an example of how incorrect variable scoping can lead to a "Cannot find symbol" error:以下是不正确的变量范围如何导致“找不到符号”错误的示例:

List<String> strings = ...

for (int i = 0; i < strings.size(); i++) {
    if (strings.get(i).equalsIgnoreCase("fnord")) {
        break;
    }
}
if (i < strings.size()) {
    ...
}

This will give a "Cannot find symbol" error for i in the if statement.这将在if语句中为i给出“找不到符号”错误。 Though we previously declared i , that declaration is only in scope for the for statement and its body.尽管我们之前声明了i ,但该声明仅在for语句及其主体的范围内 The reference to i in the if statement cannot see that declaration of i . if语句中对i的引用看不到i的声明。 It is out of scope .超出了范围

(An appropriate correction here might be to move the if statement inside the loop, or to declare i before the start of the loop.) (此处适当的更正可能是将if语句移动到循环内,或者在循环开始之前声明i 。)


Here is an example that causes puzzlement where a typo leads to a seemingly inexplicable "Cannot find symbol" error:这是一个导致困惑的示例,其中一个错字导致看似莫名其妙的“找不到符号”错误:

for (int i = 0; i < 100; i++); {
    System.out.println("i is " + i);
}

This will give you a compilation error in the println call saying that i cannot be found.这将在println调用中给你一个编译错误,说i找不到。 But (I hear you say) I did declare it!但是(我听到你说)我确实宣布了!

The problem is the sneaky semicolon ( ; ) before the { .问题是{之前的鬼鬼祟祟的分号 ( ; )。 The Java language syntax defines a semicolon in that context to be an empty statement . Java 语言语法将该上下文中的分号定义为空语句 The empty statement then becomes the body of the for loop.然后,空语句成为for循环的主体。 So that code actually means this:所以该代码实际上意味着:

for (int i = 0; i < 100; i++); 

// The previous and following are separate statements!!

{
    System.out.println("i is " + i);
}

The { ... } block is NOT the body of the for loop, and therefore the previous declaration of i in the for statement is out of scope in the block. { ... }块不是for循环的主体,因此for语句中i的先前声明超出了该块的范围


Here is another example of "Cannot find symbol" error that is caused by a typo.这是由拼写错误引起的“找不到符号”错误的另一个示例。

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

Despite the previous declaration, the tmp in the tmp(...) expression is erroneous.尽管前面有声明,但tmp tmp(...)表达式中的 tmp 是错误的。 The compiler will look for a method called tmp , and won't find one.编译器将寻找一种名为tmp的方法,但找不到。 The previously declared tmp is in the namespace for variables, not the namespace for methods.先前声明的tmp位于变量的命名空间中,而不是方法的命名空间中。

In the example I came across, the programmer had actually left out an operator.在我遇到的示例中,程序员实际上遗漏了一个运算符。 What he meant to write was this:他想写的是这样的:

int res = tmp * (a + b);

There is another reason why the compiler might not find a symbol if you are compiling from the command line.如果您从命令行编译,编译器可能找不到符号还有另一个原因。 You might simply have forgotten to compile or recompile some other class.您可能只是忘记了编译或重新编译其他一些类。 For example, if you have classes Foo and Bar where Foo uses Bar .例如,如果您有FooBar类,其中Foo使用Bar If you have never compiled Bar and you run javac Foo.java , you are liable to find that the compiler can't find the symbol Bar .如果您从未编译过Bar并且运行javac Foo.java ,您很可能会发现编译器找不到符号Bar The simple answer is to compile Foo and Bar together;简单的答案是将FooBar一起编译; eg javac Foo.java Bar.java or javac *.java .例如javac Foo.java Bar.javajavac *.java Or better still use a Java build tool;或者最好还是使用 Java 构建工具; eg Ant, Maven, Gradle and so on.例如 Ant、Maven、Gradle 等。

There are some other more obscure causes too ... which I will deal with below.还有一些其他更模糊的原因......我将在下面处理。

3. How do I fix these errors ? 3. 如何修复这些错误?

Generally speaking, you start out by figuring out what caused the compilation error.一般来说,您首先要找出导致编译错误的原因。

  • Look at the line in the file indicated by the compilation error message.查看文件中由编译错误消息指示的行。
  • Identify which symbol that the error message is talking about.确定错误消息所指的是哪个符号。
  • Figure out why the compiler is saying that it cannot find the symbol;弄清楚为什么编译器说它找不到符号; see above!看上面!

Then you think about what your code is supposed to be saying.然后你想想你的代码应该说什么。 Then finally you work out what correction you need to make to your source code to do what you want.最后,您确定需要对源代码进行哪些更正以执行您想要的操作。

Note that not every "correction" is correct.请注意,并非每个“更正”都是正确的。 Consider this:考虑一下:

for (int i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
        ...
    }
}

Suppose that the compiler says "Cannot find symbol" for j .假设编译器对j说“找不到符号”。 There are many ways I could "fix" that:我有很多方法可以“解决”这个问题:

  • I could change the inner for to for (int j = 1; j < 10; j++) - probably correct.我可以将内部for更改为for (int j = 1; j < 10; j++) - 可能是正确的。
  • I could add a declaration for j before the inner for loop, or the outer for loop - possibly correct.我可以在内部for循环或外部for循环之前j添加一个声明 - 可能是正确的。
  • I could change j to i in the inner for loop - probably wrong!我可以在内部for循环中将j更改为i - 可能是错误的!
  • and so on.等等。

The point is that you need to understand what your code is trying to do in order to find the right fix.关键是您需要了解您的代码试图做什么才能找到正确的修复程序。

4. Obscure causes 4. 不明原因

Here are a couple of cases where the "Cannot find symbol" is seemingly inexplicable ... until you look closer.以下是一些“找不到符号”看似莫名其妙的情况......直到你仔细观察。

  1. Incorrect dependencies : If you are using an IDE or a build tool that manages the build path and project dependencies, you may have made a mistake with the dependencies;不正确的依赖关系:如果您使用管理构建路径和项目依赖关系的 IDE 或构建工具,您可能在依赖关系方面犯了错误; eg left out a dependency, or selected the wrong version.例如,遗漏了一个依赖项,或者选择了错误的版本。 If you are using a build tool (Ant, Maven, Gradle, etc), check the project's build file.如果您使用的是构建工具(Ant、Maven、Gradle 等),请检查项目的构建文件。 If you are using an IDE, check the project's build path configuration.如果您使用的是 IDE,请检查项目的构建路径配置。

  2. Cannot find symbol 'var' : You are probably trying to compile source code that uses local variable type inference (ie a var declaration) with an older compiler or older --source level.找不到符号 'var' :您可能正在尝试使用较旧的编译器或较旧的--source级别编译使用局部变量类型推断(即var声明)的源代码。 The var was introduced in Java 10. Check your JDK version and your build files, and (if this occurs in an IDE), the IDE settings. var是在 Java 10 中引入的。检查您的 JDK 版本和构建文件,以及(如果这发生在 IDE 中),请检查 IDE 设置。

  3. You are not compiling / recompiling : It sometimes happens that new Java programmers don't understand how the Java tool chain works, or haven't implemented a repeatable "build process";您没有编译/重新编译:有时会发生新的 Java 程序员不了解 Java 工具链是如何工作的,或者没有实现可重复的“构建过程”; eg using an IDE, Ant, Maven, Gradle and so on.例如使用 IDE、Ant、Maven、Gradle 等。 In such a situation, the programmer can end up chasing his tail looking for an illusory error that is actually caused by not recompiling the code properly, and the like.在这种情况下,程序员最终可能会追着尾巴寻找实际上是由于没有正确重新编译代码等造成的虚幻错误。

    Another example of this is when you use (Java 9+) java SomeClass.java to compile and run a class.另一个例子是当你使用(Java 9+) java SomeClass.java来编译和运行一个类时。 If the class depends on another class that you haven't compiled (or recompiled), you are liable to get "Cannot resolve symbol" errors referring to the 2nd class.如果该类依赖于您尚未编译(或重新编译)的另一个类,则您可能会收到涉及第二类的“无法解析符号”错误。 The other source file(s) are not automatically compiled.其他源文件不会自动编译。 The java command's new "compile and run" mode is not designed for running programs with multiple source code files. java命令的新“编译和运行”模式不是为运行具有多个源代码文件的程序而设计的。

  4. An earlier build problem : It is possible that an earlier build failed in a way that gave a JAR file with missing classes.较早的构建问题:较早的构建可能以某种方式失败,导致 JAR 文件缺少类。 Such a failure would typically be noticed if you were using a build tool.如果您使用的是构建工具,通常会注意到这种失败。 However if you are getting JAR files from someone else, you are dependent on them building properly, and noticing errors.但是,如果您从其他人那里获取 JAR 文件,则您依赖于他们正确构建并注意到错误。 If you suspect this, use tar -tvf to list the contents of the suspect JAR file.如果您怀疑这一点,请使用tar -tvf列出可疑 JAR 文件的内容。

  5. IDE issues : People have reported cases where their IDE gets confused and the compiler in the IDE cannot find a class that exists ... or the reverse situation. IDE 问题:人们报告了他们的 IDE 被混淆并且 IDE 中的编译器找不到存在的类的情况......或者相反的情况。

    • This could happen if the IDE has been configured with the wrong JDK version.如果 IDE 配置了错误的 JDK 版本,则可能会发生这种情况。

    • This could happen if the IDE's caches get out of sync with the file system.如果 IDE 的缓存与文件系统不同步,就会发生这种情况。 There are IDE specific ways to fix that.有特定于 IDE 的方法来解决这个问题。

    • This could be an IDE bug.这可能是一个 IDE 错误。 For instance @Joel Costigliola described a scenario where Eclipse did not handle a Maven "test" tree correctly: see this answer .例如,@Joel Costigliola 描述了 Eclipse 没有正确处理 Maven“测试”树的场景:见这个答案 (Apparently that particular bug was been fixed a long time ago.) (显然,那个特定的错误很久以前就被修复了。)

  6. Android issues : When you are programming for Android, and you have "Cannot find symbol" errors related to R , be aware that the R symbols are defined by the context.xml file. Android 问题:当您为 Android 编程时,遇到与R相关的“找不到符号”错误,请注意R符号是由context.xml文件定义的。 Check that your context.xml file is correct and in the correct place, and that the corresponding R class file has been generated / compiled.检查您的context.xml文件是否正确并位于正确的位置,以及是否已生成/编译了相应的R类文件。 Note that the Java symbols are case sensitive, so the corresponding XML ids are be case sensitive too.请注意,Java 符号区分大小写,因此相应的 XML id 也区分大小写。

    Other symbol errors on Android are likely to be due to previously mention reasons; Android 上的其他符号错误可能是由于前面提到的原因; eg missing or incorrect dependencies, incorrect package names, method or fields that don't exist in a particular API version, spelling / typing errors, and so on.例如,缺少或不正确的依赖项、不正确的包名称、特定 API 版本中不存在的方法或字段、拼写/键入错误等等。

  7. Hiding system classes : I've seen cases where the compiler complains that substring is an unknown symbol in something like the following隐藏系统类:我见过编译器抱怨substring是未知符号的情况,如下所示

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

    It turned out that the programmer had created their own version of String and that his version of the class didn't define a substring methods.事实证明,程序员已经创建了他们自己的String版本,并且他的类版本没有定义substring方法。 I've seen people do this with System , Scanner and other classes.我见过人们用SystemScanner和其他类来做这件事。

    Lesson: Don't define your own classes with the same names as common library classes!教训:不要使用与公共库类相同的名称定义自己的类!

    The problem can also be solved by using the fully qualified names.该问题也可以通过使用完全限定名称来解决。 For example, in the example above, the programmer could have written:例如,在上面的示例中,程序员可以编写:

     java.lang.String s = ... java.lang.String s1 = s.substring(1);
  8. Homoglyphs: If you use UTF-8 encoding for your source files, it is possible to have identifiers that look the same, but are in fact different because they contain homoglyphs. Homoglyphs:如果您对源文件使用 UTF-8 编码,则可能会有看起来相同但实际上不同的标识符,因为它们包含同形文字。 See this page for more information.请参阅此页面了解更多信息。

    You can avoid this by restricting yourself to ASCII or Latin-1 as the source file encoding, and using Java \uxxxx escapes for other characters.您可以通过将自己限制为 ASCII 或 Latin-1 作为源文件编码并使用 Java \uxxxx对其他字符进行转义来避免这种情况。


1 - If, perchance, you do see this in a runtime exception or error message, then either you have configured your IDE to run code with compilation errors, or your application is generating and compiling code .. at runtime. 1 - 如果您确实在运行时异常或错误消息中看到了这一点,那么您可能已将 IDE 配置为运行出现编译错误的代码,或者您的应用程序正在运行时生成和编译代码。
2 - The three basic principles of Civil Engineering: water doesn't flow uphill, a plank is stronger on its side, and you can't push on a rope . 2 - 土木工程的三个基本原则:水不会上坡,木板的侧面更坚固,你不能推动绳索

You'll also get this error if you forget a new :如果你忘记了一个new的,你也会得到这个错误:

String s = String();

versus相对

String s = new String();

because the call without the new keyword will try and look for a (local) method called String without arguments - and that method signature is likely not defined.因为没有new关键字的调用将尝试寻找一个没有参数的称为String的(本地)方法 - 并且该方法签名可能没有定义。

One more example of 'Variable is out of scope' “变量超出范围”的另一个示例

As I've seen that kind of questions a few times already, maybe one more example to what's illegal even if it might feel okay.正如我已经多次看到这类问题的那样,也许再举一个例子来说明什么是非法的,即使它可能感觉还不错。

Consider this code:考虑这段代码:

if(somethingIsTrue()) {
  String message = "Everything is fine";
} else {
  String message = "We have an error";
}
System.out.println(message);

That's invalid code.那是无效代码。 Because neither of the variables named message is visible outside of their respective scope - which would be the surrounding brackets {} in this case.因为名为message的变量在它们各自的范围之外都不可见 - 在这种情况下,这将是周围的括号{}

You might say: "But a variable named message is defined either way - so message is defined after the if ".你可能会说:“但是一个名为 message 的变量是以任何一种方式定义的——所以 messageif之后定义的”。

But you'd be wrong.但你错了。

Java has no free() or delete operators, so it has to rely on tracking variable scope to find out when variables are no longer used (together with references to these variables of cause). Java 没有free()delete运算符,因此它必须依靠跟踪变量范围来找出何时不再使用变量(以及对这些原因变量的引用)。

It's especially bad if you thought you did something good.如果你认为你做了一件好事,那就特别糟糕了。 I've seen this kind of error after "optimizing" code like this:我在“优化”这样的代码后看到了这种错误:

if(somethingIsTrue()) {
  String message = "Everything is fine";
  System.out.println(message);
} else {
  String message = "We have an error";
  System.out.println(message);
}

"Oh, there's duplicated code, let's pull that common line out" -> and there it it. “哦,有重复的代码,让我们把那条公共线拉出来”-> 就在那里。

The most common way to deal with this kind of scope-trouble would be to pre-assign the else-values to the variable names in the outside scope and then reassign in if:处理这种范围问题的最常见方法是将 else 值预先分配给外部范围内的变量名,然后在 if 中重新分配:

String message = "We have an error";
if(somethingIsTrue()) {
  message = "Everything is fine";
} 
System.out.println(message);

One way to get this error in Eclipse :在 Eclipse 中获取此错误的一种方法:

  1. Define a class A in src/test/java .src/test/java中定义一个类A
  2. Define another class B in src/main/java that uses class A .src/main/java中定义另一个使用类AB

Result : Eclipse will compile the code, but maven will give "Cannot find symbol".结果:Eclipse 将编译代码,但 maven 会给出“找不到符号”。

Underlying cause : Eclipse is using a combined build path for the main and test trees.根本原因:Eclipse 使用主树和测试树的组合构建路径。 Unfortunately, it does not support using different build paths for different parts of an Eclipse project, which is what Maven requires.不幸的是,它不支持对 Eclipse 项目的不同部分使用不同的构建路径,而这正是 Maven 所需要的。

Solution :解决方案 :

  1. Don't define your dependencies that way;不要那样定义你的依赖关系; ie don't make this mistake.即不要犯这个错误。
  2. Regularly build your codebase using Maven so that you pick up this mistake early.定期使用 Maven 构建您的代码库,以便您尽早发现这个错误。 One way to do that is to use a CI server.一种方法是使用 CI 服务器。

SOLVED解决了

Using IntelliJ使用 IntelliJ

Select Build -> Rebuild Project will solve it选择Build -> Rebuild Project将解决它

"Can not find " means that , compiler who can't find appropriate variable, method ,class etc...if you got that error massage , first of all you want to find code line where get error massage..And then you will able to find which variable , method or class have not define before using it.After confirmation initialize that variable ,method or class can be used for later require...Consider the following example. “找不到”意味着编译器找不到合适的变量、方法、类等……如果你得到那个错误消息,首先你要找到得到错误消息的代码行……然后你会能够找到在使用之前没有定义的变量、方法或类。确认后初始化该变量、方法或类可以用于以后的需求...考虑以下示例。

I'll create a demo class and print a name...我将创建一个演示类并打印一个名称...

class demo{ 
      public static void main(String a[]){
             System.out.print(name);
      }
}

Now look at the result..现在看看结果..

在此处输入图像描述

That error says, "variable name can not find"..Defining and initializing value for 'name' variable can be abolished that error..Actually like this,那个错误说,“变量名找不到”..为'name'变量定义和初始化值可以取消那个错误..实际上像这样,

class demo{ 
      public static void main(String a[]){

             String name="smith";

             System.out.print(name);
      }
}

Now look at the new output...现在看看新的输出......

在此处输入图像描述

Ok Successfully solved that error..At the same time , if you could get "can not find method " or "can not find class" something , At first,define a class or method and after use that..好的 成功解决了那个错误..同时,如果你能得到“找不到方法”或“找不到类”的东西,首先,定义一个类或方法,然后使用它..

If you're getting this error in the build somewhere else, while your IDE says everything is perfectly fine, then check that you are using the same Java versions in both places.如果您在其他地方的构建中遇到此错误,而您的 IDE 说一切都很好,那么请检查您是否在两个地方使用相同的 Java 版本。

For example, Java 7 and Java 8 have different APIs, so calling a non-existent API in an older Java version would cause this error.例如,Java 7 和 Java 8 具有不同的 API,因此在较旧的 Java 版本中调用不存在的 API 会导致此错误。

There can be various scenarios as people have mentioned above.正如人们上面提到的那样,可能存在各种情况。 A couple of things which have helped me resolve this.有几件事帮助我解决了这个问题。

  1. If you are using IntelliJ如果您使用 IntelliJ

    File -> 'Invalidate Caches/Restart'

OR或者

  1. The class being referenced was in another project and that dependency was not added to the Gradle build file of my project.被引用的类在另一个项目中,并且该依赖项未添加到我项目的 Gradle 构建文件中。 So I added the dependency using所以我添加了依赖项

    compile project(':anotherProject')

and it worked.它奏效了。 HTH!

If eclipse Java build path is mapped to 7, 8 and in Project pom.xml Maven properties java.version is mentioned higher Java version(9,10,11, etc..,) than 7,8 you need to update in pom.xml file.如果 eclipse Java 构建路径映射到 7、8 并且在 Project pom.xml Maven 属性中提到 java.version 比 7,8 更高的 Java 版本(9、10、11 等),则需要在 pom 中更新。 xml 文件。

In Eclipse if Java is mapped to Java version 11 and in pom.xml it is mapped to Java version 8. Update Eclipse support to Java 11 by go through below steps in eclipse IDE Help -> Install New Software ->在 Eclipse 中,如果 Java 映射到 Java 版本 11,而在 pom.xml 中它映射到 Java 版本 8。通过 eclipse IDE 帮助 -> 安装新软件 -> 中的以下步骤将 Eclipse 支持更新到 Java 11

Paste following link http://download.eclipse.org/eclipse/updates/4.9-P-builds at Work WithWork With粘贴以下链接http://download.eclipse.org/eclipse/updates/4.9-P-builds

or或者

Add (Popup window will open) ->添加(将打开弹出窗口)->

Name: Java 11 support Location: http://download.eclipse.org/eclipse/updates/4.9-P-builds Name: Java 11 支持Location: //download.eclipse.org/eclipse/updates/4.9-P-builds

then update Java version in Maven properties of pom.xml file as below然后在pom.xml文件的 Maven 属性中更新 Java 版本,如下所示

<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>

Finally do right click on project Debug as -> Maven clean, Maven build steps最后右击项目Debug as -> Maven clean, Maven build steps

I too was getting this error.我也遇到了这个错误。 (for which I googled and I was directed to this page) (为此我用谷歌搜索并被定向到此页面)

Problem: I was calling a static method defined in the class of a project A from a class defined in another project B. I was getting the following error:问题:我正在从另一个项目 B 中定义的类调用项目 A 的类中定义的静态方法。我收到以下错误:

error: cannot find symbol

Solution: I resolved this by first building the project where the method is defined then the project where the method was being called from.解决方案:我解决了这个问题,首先构建定义方法的项目,然后构建调用方法的项目。

you compiled your code using maven compile and then used maven test to run it worked fine.您使用 maven compile 编译了代码,然后使用 maven test 运行它工作正常。 Now if you changed something in your code and then without compiling you are running it, you will get this error.现在,如果您更改了代码中的某些内容,然后没有编译就运行它,您将收到此错误。

Solution: Again compile it and then run test.解决方案:再次编译它,然后运行测试。 For me it worked this way.对我来说,它是这样工作的。

In my case - I had to perform below operations:就我而言 - 我必须执行以下操作:

  1. Move context.xml file from src/java/package to the resource directory (IntelliJ IDE)context.xml文件从src/java/package移动到resource目录(IntelliJ IDE)
  2. Clean target directory.清理target目录。

For hints, look closer at the class name name that throws an error and the line number, example: Compilation failure [ERROR] \applications\xxxxx.java:[44,30] error: cannot find symbol有关提示,请仔细查看引发错误的类名名称和行号,例如:Compilation failure [ERROR] \applications\xxxxx.java:[44,30] error: cannot find symbol

One other cause is unsupported method of for java version say jdk7 vs 8. Check your %JAVA_HOME%另一个原因是 java 版本不支持的方法说 jdk7 vs 8。检查你的 %JAVA_HOME%

We got the error in a Java project that is set up as a Gradle multi-project build.我们在设置为 Gradle 多项目构建的 Java 项目中遇到错误。 It turned out that one of the sub-projects was missing the Gradle Java Library plugin .结果发现其中一个子项目缺少Gradle Java 库插件 This prevented the sub-project's class files from being visible to other projects in the build.这阻止了子项目的类文件对构建中的其他项目可见。

After adding the Java library plugin to the sub-project's build.gradle in the following way, the error went away:通过以下方式将Java库插件添加到子项目的build.gradle后,错误消失了:

plugins {
    ...
    id 'java-library'
}

Re: 4.4: An earlier build problem in Stephen C's excellent answer:回复: 4.4:Stephen C 出色答案中的早期构建问题

I encountered this scenario when developing an osgi application.我在开发 osgi 应用程序时遇到了这种情况。
I had a java project A that was a dependency of B .我有一个 java 项目AB的依赖项。 When building B , there was the error:构建B时,出现错误:

Compilation failure: org.company.projectA.bar.xyz does not exist

But in eclipse, there was no compile problem at all.但是在eclipse中,根本没有编译问题。

Investigation调查
When i looked in A.jar , there were classes for org.company.projectA.foo.abc but none for org.company.projectA.bar.xyz .当我查看A.jar时,有org.company.projectA.foo.abc的类,但没有org.company.projectA.bar.xyz的类。

The reason for the missing classes, was that in the A/pom.xml , was an entry to export the relevant packages.缺少类的原因是,在A/pom.xml中,是导出相关包的条目。

<plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    ...
    <configuration>
        <instructions>
            ....
            <Export-Package>org.company.projectA.foo.*</Export-Package>
        </instructions>
    </configuration>
</plugin>

Solution解决方案
Add the missing packages like so:像这样添加缺少的包:

<Export-Package>org.company.projectA.foo.*,org.company.projectA.bar.*</Export-Package>

and rebuild everything.并重建一切。

Now the A.jar includes all the expected classes, and everything compiles.现在A.jar包含所有预期的类,并且所有内容都可以编译。

I was getting below error我得到以下错误

java: cannot find symbol
  symbol: class __

To fix this要解决这个问题

I tried enabling lambok, restarted intellij, etc but below worked for me.我尝试启用lambok,重新启动intellij等,但以下对我有用。

Intellij Preferences ->Compiler -> Shared Build process VM Options and set it to Intellij Preferences -> Compiler -> Shared Build process VM Options 并将其设置为

  -Djps.track.ap.dependencies=false

than run比跑

mvn clean install

Optional.isEmpty()可选的.isEmpty()

I was happily using .Optional.isEmpty() in my IDE, and it works fine, as i was compiling/running my project with >= JDK11 .我很高兴在我的 IDE 中使用.Optional.isEmpty() ,它工作正常,因为我正在使用 >= JDK11编译/运行我的项目。 Now, when i use Gradle on the command line (running on JDK8 ), i got the nasty error in the compile task.现在,当我在命令行(在JDK8上运行)上使用Gradle时,我在编译任务中遇到了令人讨厌的错误。

Why?为什么?

From the docs (Pay attention to the last line):从文档(注意最后一行):

boolean java.util.Optional.isEmpty()

If a value is not present, returns true, otherwise false.
Returns:true if a value is not present, otherwise false
Since:11

Please explain the following about "Cannot find symbol", "Cannot resolve symbol" or "Symbol not found" errors:请解释以下有关“找不到符号”,“无法解析符号”或“找不到符号”错误的信息:

  • What do they mean?他们的意思是什么?
  • What things can cause them?什么事会导致它们?
  • How does the programmer go about fixing them?程序员如何进行修复?

This question is designed to seed a comprehensive Q&A about these common compilation errors in Java.该问题旨在对Java中的这些常见编译错误进行全面的问答。

What do they mean?他们的意思是什么?<\/h1> All three statements are means same things: "Cannot find symbol", "Cannot resolve symbol", and "Symbol not found".这三个语句的含义相同:“找不到符号”、“无法解析符号”和“找不到符号”。

Now, the meaning of the error is that Compiler is unable to understand the reference of defined symbol.现在,错误的含义是编译器无法理解定义符号的引用。 Or simply Compiler can't do this.或者只是编译器无法做到这一点。

Cause & How to FIX原因和如何解决<\/h1>

If you're getting this error in the build somewhere else, while your IDE says everything is perfectly fine, then check that you are using the same Java versions in both places.如果您在其他地方的构建中遇到此错误,而您的 IDE 说一切都很好,那么请检查您是否在两个地方使用相同的 Java 版本。 If you encounter this error in a build elsewhere, and your IDE says that everything is fine, please check if the same Java version is used in both places.<\/strong>如果您在其他地方的构建中遇到此错误,并且您的 IDE 说一切正常,请检查两个地方是否使用了相同的 Java 版本。<\/strong>

For example, Java 7 and Java 8 have different APIs, so calling a non-existent API in an older Java version would cause this error.例如,Java 7 和 Java 8 具有不同的 API,因此在较旧的 Java 版本中调用不存在的 API 会导致此错误。 For example, Java 7 and Java 8 have different APIs, so calling a non-existent API in an older Java version will cause this error.<\/strong>例如,Java 7 和 Java 8 有不同的 API,因此在较旧的 Java 版本中调用不存在的 API 会导致此错误。<\/strong>

"

I got this error after importing class files into my new Eclipse project (including a Main class file).将类文件导入我的新 Eclipse 项目(包括主类文件)后,我收到此错误。 After trial and error, I fixed it by moving the class files that caused this error to my src folder and setting my Run Configurations to the exact name of my Main class.经过反复试验,我通过将导致此错误的类文件移动到我的 src 文件夹并将我的运行配置设置为我的主类的确切名称来修复它。

我在编译我的项目时遇到了同样的问题,我检查了我的 java 编译器版本,它曾经在 java 1.8 上工作,但不小心设置为 java 17,我将它改回版本 1.8,我的问题得到解决。

在此处输入图像描述

I solved this error like this... The craziness of android.我像这样解决了这个错误......android的疯狂。 I had the package name as Adapter and the I refactor the name to adapter with an "a" instead of "A" and solved the error.我将包名称作为适配器,并且我将名称重构为使用“a”而不是“A”的适配器并解决了错误。

Please explain the following about "Cannot find symbol", "Cannot resolve symbol" or "Symbol not found" errors (in Java):请解释以下有关“找不到符号”、“无法解析符号”或“找不到符号”错误(在 Java 中)的说明:

  • What do they mean?他们的意思是什么?
  • What things can cause them?什么事情会导致它们?
  • How does the programmer go about fixing them?程序员如何修复它们?

This question is designed to seed a comprehensive Q&A about these common compilation errors in Java.这个问题旨在就 Java 中这些常见的编译错误进行全面的问答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM