Меню

Cannot resolve symbol java intellij idea ошибка

This problem happens intermittently for different libraries and different projects.
When trying to import a library, the package will be recognized, but the class name can’t be resolved.

If on the import statement, I right-click -> Goto -> the package's declaration, I see all the decompiled classes displayed in the side pane — Including the ones I need —
If I try to auto-complete the import statement, I notice the class I need is not featured in the dropdown.

I tried invalidating caches already, doesn’t work. I cannot find any class conflicts — there is no other jar file in my classpath with the same package name.
I am able to import this class into other projects.

Please see screen shots:

Anyone have a clue?

Ivar's user avatar

Ivar

5,85012 gold badges53 silver badges60 bronze badges

asked Nov 15, 2014 at 23:39

a5af's user avatar

5

You can try invalidating the cache and restarting IntelliJ, in many cases it will help.

File -> Invalidate Caches/Restart

Ivar's user avatar

Ivar

5,85012 gold badges53 silver badges60 bronze badges

answered Dec 16, 2014 at 16:01

sahitya's user avatar

sahityasahitya

4,9102 gold badges9 silver badges12 bronze badges

10

There can be multiple reasons for this. In my case it was wrong source root issue. Invalidate caches didn’t work along with other solutions.

Check your module source roots.

  1. Project Structure (Ctrl+Alt+Shift+S).

  2. Modules

  3. Select your problem module.

  4. Change tab on top of window «Sources».

  5. Remove unwanted source roots. Keep one and add src and test source roots in this root.

inetphantom's user avatar

inetphantom

2,4203 gold badges39 silver badges61 bronze badges

answered Oct 7, 2015 at 17:54

Vipin Thomas's user avatar

4

File -> Invalidate Caches/Restart
And
Build your project

TuGordoBello's user avatar

TuGordoBello

4,1939 gold badges50 silver badges75 bronze badges

answered Feb 13, 2018 at 4:14

Harsh Mishra's user avatar

Harsh MishraHarsh Mishra

1,90711 silver badges15 bronze badges

0

IntelliJ has issues in resolving the dependencies.
Try the following:

  1. Right click on pom.xml -> Maven -> Reimport
  2. Again Right click on pom.xml -> Maven -> Generate sources and update folders

Joern Boegeholz's user avatar

answered Feb 2, 2018 at 19:24

Chandlersingh's user avatar

3

Run this command in your project console:

mvn idea:idea

Done.
Had this issue many times. Tried ‘Invalidate Cache & Restart’ and all other solutions. Running that command works perfect to me.
I’m currently using IntelliJ 2019.2, but this also happened in previous versions and solution worked as well.

answered Sep 11, 2019 at 16:12

Liuver Reynier Durán Pérez's user avatar

5

File -> Invalidate Caches/Restart or rebuilding the project did not work wor me.

What worked for my Gradle project was to «Refresh all Gradle projects» from the Gradle tab on top-right corner of IntelliJ v2017, using the yellow marked button shown below:

enter image description here

answered Jun 25, 2018 at 13:20

eaykin's user avatar

eaykineaykin

3,6331 gold badge35 silver badges33 bronze badges

1

Check your module dependencies.

  1. Project Structure (Ctrl+Alt+Shift+S).
  2. Modules
  3. Select your problem module.
  4. Change tab on top of window «Dependencies».
  5. Check what needed library (maybe, you need to add specified library
    in the tab ‘libraries’) or module has listed here and it has right
    scope (‘complile’ mostly).

Jordi Castilla's user avatar

answered Sep 3, 2015 at 9:18

Artem Moiseyenko's user avatar

0

I faced a similar issue, Mike’s comment helped me move in the direction to solve it.
Though the required library was a part of the module in my project too, it needed a change of scope. In the module dependency, I changed the scope to «Compile» rather than «Test» and it works fine for me now.

answered Apr 30, 2015 at 10:50

minx's user avatar

minxminx

1862 silver badges9 bronze badges

0

Had the same problem till I noticed that the src folder was marked as root source instead of java!
Changing to only the java (src/main/java) to be the source root solved my problem
enter image description here

answered Jul 11, 2018 at 22:31

Pipo's user avatar

PipoPipo

4,37537 silver badges45 bronze badges

0

I found the following answer from @jossef-harush and @matt-leidholm useful from another link

  • in IntelliJ editor, click on the red keyword (Integer for example) and press ALT + ENTER (or click the light bulb icon)
  • select Setup JDK from the intentions menu

IntelliJ intentions menu

  • click on Configure

Project SDK selection dialog

  • In my case, the JDK path was incorrect (pointed on /opt/jdk1.7.0_51 instead of /opt/jdk1.7.0_65)

Broken Configure SDK dialog

  • click on the ... and browse to the right JDK path

Fixed Configure SDK dialog

  • let’s clear the cache

IntelliJ File menu

answered Oct 28, 2017 at 17:40

manntsheth's user avatar

manntshethmanntsheth

4406 silver badges8 bronze badges

Right click on pom.xml file, go to Maven click on Reimport. I had similar problem and this worked for me.

answered Sep 18, 2018 at 5:35

rdutta's user avatar

rduttardutta

1051 silver badge5 bronze badges

After a long search, I discovered that a dependency was somehow corrupted on my machine in a maven project. The strange thing was that the dependency was still working correctly in the compiled java code. When I cleaned and rebuilt my maven dependency cache however, the problem went away and IntelliJ recognized the package. You can do this by running:

mvn dependency:purge-local-repository

Intrestingly, the source of my problem hence wasn’t IntelliJ, but maven itself.

answered Feb 14, 2019 at 13:46

JohannesB's user avatar

JohannesBJohannesB

1,95521 silver badges34 bronze badges

For 2020.1.4 Ultimate edition, I had to do the following

View -> Maven -> Generate Sources and Update Folders For all Projects

The issue for me was the libraries were not getting populated with
mvn -U clean install from the terminal.

enter image description here

answered Jul 25, 2020 at 2:29

user1599755's user avatar

Try cleaning maven from upstream by:

  mvn -U clean install

answered Jul 27, 2021 at 12:56

Bablu's user avatar

BabluBablu

1317 bronze badges

I also got this error for multiple times when I try to build a new java project.

Below is the step how I got this stupid issue.

  1. Create an empty project, and create new directory src/main/java.
  2. Create the source package net.gongmingqm10.sketch.
  3. Use gradle wrapper, gradle idea to build the gradle stuff for the project.
  4. Add some dependencies in build.gradle file, and gradle build, reimport the project.
  5. Create User.java and School.java in the existing package net.gongmingqm10.sketch
  6. I got the error while I try to use import School in User.java.
  7. Intellij keeps complain can not resolve symbol on import.

Solution:

Build the project first, and mark the main/java as the source root. Create a new directory with the same name net.gongmingqm10.sketch. Move all the files from the old troubling packages to new package.

Root cause:

Directory tree of source code

As you can see from the tree. I got a directory named net.gongmingqm10.sketch. But what we really need is the 3 levels directory: net->gongmingqm10->sketch

But before I finish building my project in Intellij, I create new directory named net.gongmingqm19.sketch, which will give me a real directory with the name net.gongmingqm10.sketch.

When we trying to import it. Obviously, how can intellij import the file under the weired directory with the name a.b.c.

answered Aug 19, 2016 at 17:59

Ming Gong's user avatar

1

@Anton Dozortsev I was driven crazy by a similar behavior; I ended up re-installing the IDE a bunch of times, only getting past the issue after removing the IDEA app, all caches, preferences, etc.

I tried all kinds of steps in the interim, (like restarts, invalidations, deleting .idea and *.iml files, and others.)

Turns out, the problem was due to IntelliJ’s idea.max.intellisense.filesize setting. I had set it to 100KB, which was smaller than my dependency’s size, leading to IntelliJ showing it as unknown, just like in your screenshot.

Fix:

  1. Click on Help -> Edit Custom Properties

  2. Set the property to a larger value; the default is 2500KB
    idea.max.intellisense.filesize=2500

answered Jun 12, 2017 at 17:09

Mihai Bojin's user avatar

Please try File-> Synchronize. Then close and reopen IntelliJ before you invalidate.

Once I restarted. I would have invalidated but the synchronize cleared everything after restarting.

answered Jul 30, 2019 at 15:28

Adam M. Erickson's user avatar

Simple Restart worked for me.

I would suggest first try with restart and then you may opt for invalidating the cache.

PS : Cleaning out the system caches will result in clearing the local history.

answered Dec 9, 2016 at 23:02

neoguy's user avatar

I found the source cause!

In my case, I add a jar file include some java source file, but I think the java source is bad, in Intellij Idea dependency library it add the source automatic, so in Editor the import is BAD, JUST remove the source code in «Project Structure» -> «Library», it works for me.

answered Apr 23, 2017 at 0:02

crazycode's user avatar

crazycodecrazycode

1411 silver badge3 bronze badges

What did it for me is to edit the package file in the .idea folder as I accidentally added sources to this jar library and android couldn’t resolve it by deleting the sources line as marked in the b/m picture library error.

Then rebuild the gradle and bam problem solved.

demongolem's user avatar

demongolem

9,31636 gold badges89 silver badges104 bronze badges

answered May 1, 2017 at 17:06

mario's user avatar

I had the same issue and the reason for that was incorrect marking of the project’s sources.

I manually created the Root Content and didn’t notice that src/main/test folder was marked as Sources instead of Tests. So that is why my test classes were assumed to have all their test libraries (JUnit, Mockito, etc.) with the scope of Compile, not Test.

As soon as I marked src/main/test as Tests and rebuilt the module all errors were gone.

Donald Duck's user avatar

Donald Duck

8,05922 gold badges73 silver badges93 bronze badges

answered Jun 5, 2017 at 12:40

Евгений Гордиенко's user avatar

I had this recently while trying to use Intellij to work on NiFi, turned out the issue was that NiFi requires Maven >= 3.1.0 and the version that I’d checked out with (I guess my default) was 3.0.5. Updating the Maven version for the project fixed it, so in some cases Maven version mis-alignment can be a thing to look…I’d guess it’s fairly unusual but if you get this far on the thread you’re probably having an unusual issue 🙂

answered Jan 3, 2018 at 18:54

Isaac's user avatar

IsaacIsaac

1,48515 silver badges8 bronze badges

file-> Project Structure -> Modules, find the module with problems, click it and choose the Dependencies tab in the right side. Click the green plus sign, try to add the jar or libraries that cause the problem. That works for me.

answered Oct 25, 2018 at 11:58

SteveHu's user avatar

Nothing I tried above worked for me (not that I tried every suggestion). What finally did the trick was to rename the class — I just added a 2 to the class name and filename. Then I resolved all the references manually. (Since they weren’t recognized, the refactoring did not change the references automatically.)

Once the «2-version» was happily resolved everywhere, I was then able to refactor and remove the 2 from the class and file, and everything was then as it should be.

answered Dec 24, 2019 at 21:59

greymatter's user avatar

greymattergreymatter

8161 gold badge9 silver badges25 bronze badges

in my case the solution was to add the project as maven project, besides the fact that i imported as maven project 😛

go to pom.xml -> right click -> add as maven project

answered Jan 29, 2020 at 10:42

lempesis's user avatar

My issue was my Maven plugin got disabled after an update. I went to Help -> Find Action… -> Typed in Maven and found that it was «Off». I clicked the toggle switch and after a bit of loading it was re-enabled.

answered May 18, 2021 at 15:32

Rjbeckwith's user avatar

RjbeckwithRjbeckwith

7208 silver badges16 bronze badges

Also, check your class is not in compile exclusions

If you see, that there is a little grey cross in left top corner, you must remove class from compile exclusions

enter image description here

How to remove

enter image description here

enter image description here

answered May 26, 2021 at 13:29

Bestows In Constructing's user avatar

Old question, ’21 response. I ran into the issue where my go build would build code successfully but my Goland IDE showed missing modules or dependencies. I tried Invalidating Caches and Restart, but had the same problem. From another S/O thread, I tried adding the GO111MODULE=on to my Path Variables, but that didn’t resolve the IDE problems either.

What worked for me was picking the correct GOROOT path in Preferences > Go > GOROOT.

I had two versions of go installed, one by brew and one from the online Go installer. I selected the brew install path, and my IDE was able to resolve the dependencies properly.

answered Oct 25, 2021 at 20:24

Sondering Narcissist's user avatar

I’ve tried all the complicated methods and they didn’t work, since I was too lazy to re-import the project I tried something else.
Mine is a gradle project, so I went to my gradle.build file, removed the dependency, refreshed the dependencies, then added the dependency again and refreshed again, the imports started working after that.

Dharman's user avatar

Dharman

29.2k21 gold badges79 silver badges131 bronze badges

answered Jan 24, 2022 at 13:11

Elen Mouradian's user avatar

Elen MouradianElen Mouradian

3551 gold badge4 silver badges12 bronze badges

Faced similar issue,
I Updated Intellij and error start coming — Can’t Resolve Symbols.

Went to Plugins, Updated the plugins & Restart
Problem Solved !!

answered Apr 13, 2022 at 15:05

Rajat Goyal's user avatar

How to fix IntelliJ cannot resolve symbol

Thursday 08, October 2015   |   Post link

Ever since copying a Gradle project from one computer to another I have been getting ‘cannot resolve symbol String’ and similar messages in IntelliJ. Listed below are steps which *may* fix the problem:

  • Invalidate and refresh the IntelliJ’s caches

    File Menu -> Invalidate Caches / Restart
  • Project SDK selection
    Check project settings from File Menu -> Project Structure
    Ensure an SDK is selected for the Project SDK. If is selected, click the ‘New’ button, select JDK and then select the correct path to the JDK e.g. /opt/java/jdk1.8 or c:JavaJdk1.8

    intellij-project-settings.png
  • Corrupt JDK
    There may be a problem with your JDK installation, re-install JDK
  • Re-import the project

    Close the project if it is open in IntelliJ
    Delete the .idea folder in the project source code folder.
    Start IntelliJ and Import the project.

IntelliJ IDEA 2017.2

Я знаю, что об этом спрашивали, но я испробовал все найденные исправления, как показано ниже.

Каждый символ в моем коде Java содержит ошибку Cannot resolve method или Cannot resolve symbol. Тем не менее, код по-прежнему компилируется и выполняется с 0 ошибками. Сообщения об ошибках в среде IDE запускались при первом открытии проекта на 3 отдельных компьютерах, но на четвертом работают нормально … Я не могу найти ничего другого на этом четвертом компьютере.

У меня есть следующие инструкции из этой проблемы :

File -> Invalidate Caches / Restart

I deleted the [IDEA system](https://intellij-support.jetbrains.com/hc/en-us/articles/206544519-Directories-used-by-the-IDE-to-store-settings-caches-plugins-and-logs) directories, and re-imported the Maven project.

I have re-imported the Maven project

I re-imported the project with auto-import

Я также следовал инструкциям от этот вопрос:

File -> Synchronize

Тогда

File -> Invalidate Caches / Restart

А также решения здесь:

Проверьте исходные корни

Ctrl+Alt+Shift+S

Не было ошибок или исправлений в исходных корнях модуля или зависимостях модуля.

Я также попытался повторно импортировать с проверкой «Поиск проектов рекурсивно» в соответствии с рекомендациями здесь.


< Сильный > Edit1

Это не скриншот из моего реального кода, но мои ошибки выглядят так же, как скриншоты с этот пост.

enter image description here

< Сильный > EDIT2

Я только что нашел ошибку, которую не видел раньше. Когда я перехожу к Структуре проекта (Ctrl + Alt + Shift + S) в разделе Библиотеки, я вижу следующие ошибки.

enter image description here

Я проверил показанное /home/user/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7-sources.jar местоположение, и оно не существует. У меня есть antlr-2.7.7.jar, но я не уверен, нужно ли мне загружать antlr-2.7.7.7-sources.jar или просто указать моей библиотеке на .jar, который у меня есть (так как я не знаю, каковы эти настройки делать)

5 ответов

Лучший ответ

Ответом было построчно просмотреть файл pom.xml и посмотреть, какие у меня были зависимости. Я думал, что это проблема конфигурации, но это не так.

Я не заметил, что у меня не было плагина lombok, который был зависимостью для моего проекта.

Проблема, указанная в EDIT2 , на самом деле не была проблемой, так как все классы были доступны.


3

trueCamelType
3 Авг 2017 в 18:51

Поскольку ваш проект компилируется и успешно выполняется с mvn clean install, вы знаете, что ваш pom действителен.

Учитывая это, я бы порекомендовал:

  1. CloseIntelliJ
  2. удалите каталог .idea и все файлы *.iml, *.ipr для каждого из ваших модулей. Не волнуйтесь, IntelliJ создаст их заново. Сделайте резервную копию, переименовав их, если вы действительно обеспокоены.
  3. Откройте IntelliJ и найдите мастер нового проекта.
  4. Найдите возможность импортировать из существующего проекта Maven
  5. Выберите пом для вашего корневого проекта


2

Val H
15 Авг 2017 в 21:43

Проверьте правильность настроек модуля. Откройте структуру проекта ( Ctrl + Alt + Shift + S ) и проверьте, что настройки каталога источника на вкладке «Источник» действительный.

Вы используете проект maven, удалите папку .m2 и обновите проект maven, очистите проект, перестройте его и запустите … Некоторое время в проекте maven возникают проблемы такого типа, которые решаются путем перестроения проекта. также проверьте версию вашей зависимости.


-1

Anshul Sharma
3 Авг 2017 в 05:01

Это странно. Я столкнулся с той же проблемой, перебрал все вопросы по stackoverflow и другим форумам и применил все предложения в некоторой степени для переустановки intelliJ.

Хотя проблема в моем случае заключалась в том, что я исключил некоторые файлы, а именно .gradle и build build, что определенно звучит важно. Должно быть, я сделал это, чтобы исключить его из уведомлений о состоянии git, но каким-то образом я исключил его из своего проекта, поскольку я новичок в intellij. Чтобы проверить, исключены ли какие-либо из ваших папок, перейдите в раздел -> Перейти к -> модулям CTRL + Shift + Alt + s и проверьте наличие красных элементов, возможно, вам следует включить те, которые необходимы здесь.

Надеюсь, что это поможет немногим из них.


0

Bimal Gupta
2 Май 2020 в 14:58

When I import a maven project, I always report an error. Find some solutions online and analyze possible causes

A solution for the reference script house:

First problem

1, check the project’s pom file, whether the necessary dependencies are clearly written

2, whether to use your own private library

3, after the dependency is added correctly, check if the local class is downloaded.

Second type of problem

1, SDK configuration

2, Maven configurationFinal cause

File->settings->Build,Exe…->Build Tools->Maven

before fixing:

Maven home directory is the local Maven installation path

Profile in the user settings file for idea-maven

Local repository is the warehouse path for idea-maven

After modification:

Uniform to local maven configuration file and warehouse address

This is the end. The problem is solved!Then compile it in maven projects, and already start downloading the required jar package.

summary:

Encountered a large-scale error with «Cannot Resolve Symbol», the first consideration of maven configuration problems (path is wrong, and settings.xml file configuration, etc.), followed by jdk versions such as 1.7 and 1.8, scala-sdk version, etc.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Cannot read property tolowercase of undefined ошибка
  • Cannot read property createobjectasync of undefined ошибка при подписании