Class Not Found Exception when running JUnit test - java

I am getting this error when running JUnit test in Eclipse:
Class not found com.myproject.server.MyTest
java.lang.ClassNotFoundException: com.myproject.server.MyTest
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClass(RemoteTestRunner.java:693)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClasses(RemoteTestRunner.java:429)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
I've tried adding JUnit library in the classpath although I'm using maven, and the JUnit library is in the POM dependency.
I already have tried cleaning the project and created a new JUnit test case using the JUnit plugin for Eclipse, still getting the same error.

This appears to occur because only the source code is compiling when you use mvn clean compile (I'm using maven 3.1.0 so I'm not sure if it always behaved like this).
If you run mvn test, the test code will compile as well, but then it runs the tests (which may not be immediately desirable if you're trying to run them through Eclipse.) The way around this is to add test-compile to your Maven command sequence whenever you do a mvn clean. For example, you would run mvn clean compile test-compile.

I had a similar problem with my tests and found somewhere in the Web, that you have to go to Build Path in your project's properties and move Maven Dependencies above JRE System Library. That seems to have worked for me.

I faced the same problem and I was able to fix it using #slomek's answer but the issue resurfaced after that.
I finally fixed it by adding my project's output folder to the JUnit test's run configuration. Steps are:
Find your project's output folder from Project properties -> Java Build Path -> Default output folder
Usually this is <project-folder>/bin
Go to Run -> Run Configurations...
Click on the unit test's run configuration and click on the Classpath tab
Explicitly add your project's output folder under User Entries - even if the project is already included there
Click on Advanced -> Add folder to add the output folder
This issue might be due to weird project setup in Eclipse - e.g. source folder with nested maven projects imported as a single project/folder (at least that was how my project was setup).

If this problem occurs in Eclipse only, executing command Project -> Clean... on selected project may help.

After having tried everything here with no improvement, I solved my issue by just restarting Eclipse

I fixed my issue by running maven update.
Right click project your project > Maven > Update Project

In my case I had a wrong maven directory structure.
Which should be like:
/src/test/java/ com.myproject.server.MyTest
After I fixed that - everything worked like a charm.

In my case, only next steps helped me to resolve this issue:
Project->properties->Run/Debug Settings.
In "Launch configurations for '.....'" select classes/projects
Edit -> Classpath -> "Restore Default Entries"

I had the similar problem with my Eclipse Helios which debugging Junits. My problem was little different as i was able to run Junits successfully but when i was getting ClassNotFoundException while debugging the same JUNITs.
I have tried all sort of different solutions available in Stackoverflow.com and forums elsewhere, but nothing seem to work. After banging my head with these issue for close to two days, finally i figured out the solution to it.
If none of the solutions seem to work, just delete the .metadata folder created in your workspace. This would create an additional overhead of importing the projects and all sorts of configuration you have done, but these will surely solve these issue.
Hope these helps.

Earlier, in this case, I always did mvn eclipse:eclipse and restarted my Eclipse and it worked. After migrating to GIT, it stopped working for me which is somewhat weird.
Basic problem here is Mr Eclipse does not find the compiled class.
Then, I set the output folder as Project/target/test-classes which is by default generated by mvn clean install without skipping the test and proceeded with following workaround:
Option 1: Set classpath for each test case
Eclipse ->Run ->Run Configurations ->under JUnit->select mytest -> under classpath tab->Select User Entries->Advanced->Add Folder -> Select ->Apply->Run
Option 2: Create classpath variable and include it in classpath for all the test cases
Eclipse ->Windows ->Classpath Variables ->New->[Name : Junit_test_cases_cp | path : ]->ok
Then go to
Eclipse->Run ->Run Configurations ->JUnit->select mytest ->under classpath tab ->Select User Entries->Advanced->Add classpath variables->Select Junit_test_cases_cp->ok->Apply->Run
This is the only thing currently working for me after trying all the suggestions online.

NoClassDefFoundError really means it can't initilize the class. It has nothing to do with finding the class. I got this error when calling trim() on a null String.
JUnit won't show NullPointerException. The string isn't null when running normally because
I'm fetching the string from a properties file which is not availible for tests.
My advice is to remove pieces from the class until your tests start passing. Then you can determine which line is giving the error.

In my case, changing the order of Maven Dependencies from Build Path configuration did not work for me. I changed its order from Run configuration.
Follow these steps:
• Go to Run -> Run Configurations...
• Click on the unit test's run configuration and click on the Classpath tab.
• check Use temporary JAR to specify classpath (to avoid classpath length limitations).
May be it is enough and your test works. You should try, so press Run button. If it did not work. Follow all previous steps again and without pressing Run button, go to the next step.
• In sub branches of User Entries move Maven Dependencies above your project or test class.
• Click Run button.

These steps worked for me.
Delete the content of local Maven repository.
run mvn clean install in the command line. (cd to the pom directory).
Build Project in Eclipse.

1- mvn eclipse:eclipse
2- project clean all projects
3- restart

It's worth mentioning as another answer that if you're using eGit, and your classpath gets updated because of say, a test coverage tool like Clover, that sometimes there's a cleanup hiccup that does not completely delete the contents of /path/to/git/repository/<project name>/bin/
Essentially, I used Eclipse's Error Log View, identified what was causing issues during this cleanup effort, navigated to the source directory, and manually deleted the <project name>/bin directory. Once that finished I went back to Eclipse and refreshed (F5) my project and the error went away.

It can also be due to "[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?"

I had the same problem with a Gradle project with a test SourceSet with two resource directories.
This snippet comes from a main-module.gradle and adds a resource dir to the test SourceSet:
sourceSets {
test {
resources {
srcDir('../other-module/src/test/resources')
}
}
}
Doing this I had two resource directories related to the test SourceSet of the project main-module:
../other-module/src/test/resources
src/test/resources (relative to the main-module folder, automatically added by the java plugin)
I find out that if I had two files with the same name in both the source directories, something in the process resources stage went wrong. As result, no compilation started and for this reason no .class were copied in the bin directory, where JUnit was looking for the classes. The ClassNotFoundException disappeared just renaming one of the two files.

It seems compile issue. Run project as Maven test, then Run as JUnit Test.

For project that does not use maven : This worked for me https://ihategeek.wordpress.com/2012/04/18/eclipse-junit-test-class-not-found/
Adding the jre and project src at the bottom in Order and exports in build path

Pls check if you have added junit4 as dependency.
e.g
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

For me I had to put the project x/src/test/java/ at the bottom of the "order and export" in the "java build path"

Check if your project is opened as a Maven project and not just a regular Java project. Actually a no-brainer, but that is exactly the same reason why you might miss it.

I had faced the same issue. I solved it by removing the external JUnit jar dependency which I added by download from the internet externally. But then I went to project->properties->build path->add library->junit->choosed the version(ex junit4)->apply.
It automatically added the dependency. it solved my issue.

Making some dummy change and saving the test class can solve the problem. It will build the .class automatically

Might be you forgotten to place the Main class and Test Case class in
/src/test/java. Check it Once.

Related

IntelliJ does not recompile/build maven project

I am running into problems when using IntelliJ for Spring development. At first, the IntelliJ build command works fine and picks up changes I make to the source code. At some point, this stops working and I can only compile my sources through maven, as the build or rebuild project commands seem to do nothing anymore.
I am confused, as it works as desired at the start but then stops working at some point.
Steps to recreate:
Create a new Spring project using Spring Initializr:
curl https://start.spring.io/starter.zip -d type=maven-project -d javaVersion=11 -o demo.zip && unzip demo.zip
Start IntelliJ from the command line in that folder, this will auto-import the project: idea64 .
Write a log message in the main class and run the project using Run->Run 'DemoApplication'. This compiles the sources to the target folder and starts up the project. You should see the log message
Alter the log message, run again and the changes should be visible (so far so good)
Now re-compile the sources via maven command mvn compile and restart IntelliJ
From now on, running build or rebuild project within IntelliJ will not pick up any changes I make to any of my source files. In fact both commands don't seem to do anything at all. I have to compile via maven in order to properly compile my sources
I tried a few things to overcome this problem, but without success:
Invalidated caches/restart
Checked project settings for Project Compiler Output and set it to <project-folder>/target
Checked project settings/modules for output path and test output path and put in the path as above
Used Reimport All Maven Projects
Deleted the .idea folder within the project folder. This seems to work, but is very inconvenient and surely no intended behavior. Also it breaks again if I recreate the steps detailed above.
Is anyone experiencing similar problems and/or has a solution?
So for anyone running into the problems I described above:
Apparently deleting the .idea folder and restarting IntelliJ does indeed do the trick. The folder is recreated on restart and afterwards I'm able to switch between compiling within IntelliJ using run, build or rebuild project and compiling through maven goals (mvn compile, mvn test, mvn surefire:test, ...). This persists through restarts of IntelliJ such that I don't have to repeat this everytime I open a project.
I still don't know why this behavior happens, but it's a solution I'm happy to work with as long as I only have to do it every now and then for a project.
Sounds like do don't want Intellij's default build. You want Intellij to forward the build command to mvn. I assume this because you do not mention this step in your question.
Here's a screenshot that shows how to enable it:
More detail is available in the Intellij documentation https://www.jetbrains.com/help/idea/delegate-build-and-run-actions-to-maven.html#delegate_run_action

Java project runs in IDE (IntelliJ Idea) but fails to run after Maven build

I have a Java project that is ready to ship, but i have stumbled at the last hurdle. The program runs fine in the IDE, but after i run mvn clean install and the target jar is created successfully, the application fails both on the command line AND in the IDE. I can get it to run again in the IDE by doing a rebuild from within the IDE.
Has anyone else experienced something similar?
The error after the mvn clean install is
2014-08-08_10:38:20.328 INFO coza.modh.fxplatform.Controller - Application start
2014-08-08_10:38:20.344 INFO c.m.f.c.p.DataSourceFactory - Connecting to Database.
2014-08-08_10:38:20.499 INFO coza.modh.fxplatform.Controller - Model created
Exception in thread "main" java.lang.NullPointerException
at coza.modh.fxplatform.view.MainView.<init>(MainView.java:46)
at coza.modh.fxplatform.Controller.startup(Controller.java:40)
at coza.modh.fxplatform.Application.main(Application.java:7)
The line it fails on looks like this:
setContentPane(contentPane);
If i rebuild from within the IDE then the variable is not null when it gets here, but after the mvn command the variable is null when it gets to this point.
EDIT: Someone pointed out that it might be related to the fact that i used the intelliJ GUI designer tools and that Maven might not gel with it. Possibility?
I had a similar problem today. To solve the issue -
Firstly, add the following to the pom.xml
<dependency>
<groupId>com.intellij</groupId>
<artifactId>forms_rt</artifactId>
<version>5.0</version>
</dependency>
Secondly, as you stated, use the correct maven plugin to create the build.
See this for step by step instruction.
Unlikely that contentPane is null, but check. Do a clean build anyway. Maybe the line number is not entirely correct.
Normally the problem are resources, like an application icon.
They are not File but zipped inside the jar.
So paths like /src/main/resources/... will not do.
Neiter using a backslash \, and
furthermore the file paths are case sensitive.
This can be caused by different library versions, do you have changed the build path in Eclipse? (Project->Properties->Build Path -> Libraries). There should only be "JRE System Library". If there is more, then it is possible that it is be loaded instead of one of your Maven dependencies. You using "mvn clean install" means it is compiled against the Maven dependencies and thus it runs differently.
Install Maven on the system(not having IDE) before running the code
ensure you've got system property M2_HOME set to your Maven installation location and also Maven bin folder added to PATH
go to the directory,containing pom.xml of your project and type "mvn install" plus Enter to build your project
if it's for example simple project,packaged as JAR,you can run it then by typing something like this in the console:
$ java -cp target/simple-1.0-SNAPSHOT.jar org.yourcompany.projectNam.App
and Enter

Compiler error "archive for required library could not be read" - Spring Tool Suite

I am starting to configure my development environment and I am using Spring Tool Suite 2.8.1 along with m2E 1.01.
As far as I can tell, since this is a Maven Project (my first), my Maven POM is dictating (along with m2E smarts) my project build configuration and dependencies.
What I would like to know is why my IDE is displaying Java Build Problems that read "Archive required for library library/path/somejar.jar cannot be read or is not a valid zip file" when I can see the jars in my .m2 repository?
All the errors pertained to commons-logging:1.1.1 which I excluded in my parent-pom. This was a transistive dependancy via spring-context-support:3.0.5. I excluded that library from my build and now the errors pertain to the spring-context-support library.
I have attached a screenshot to illustrate.
Indeed IDEs often cache the local repository (Eclipse does something similar, and I have to relaunch Eclipse).
One ugly maven behavior you might encounter is that if you declare a dependency before you actually install it, maven will create an empty version of the missing dependency (folder with metadata but no jar), and you will have to manually clean your .m2 repository.
Third, an installed archive (jar...) can get corrupted, so try to open it with any archive tool (7zip...) to test it, and delete the whole folder if the archive is corrupted.
In my case I had to manually delete all the files in .m2\repository folder and then open command prompt and run mvn -install command in my project directory.
I was using Eclipse as IDE and I was getting very same error. I had to do Project->Maven->Update Project. Select all the checkboxes below except "offline" esp. the one "Force update of snapshots/releases" and click OK. Did the Clean Build for the Project again.
Delete corrupted files from your local .m2 repository and Ctrl+F5 (Update Maven Project) in Eclipse/STS. It'll download and install these files.
This worked for me.
Close Eclipse
Delete ./m2/repository
Open Eclipse, it will automatically download all the jars
If still problem remains, then right click project > Maven > Update Project... > Check 'Force Update of Snapshots/Releases'
Below Steps resolved my issue.
Go to ./m2/repository folder.
Go to respective archive error folder.
Verify any zip file is exist.
delete error name folder.
Now come to Eclipse Project - Right Click - Maven - > Update Project.
Above trick works for me.
For Googlers:
In my case I had accidentally manually added a Java class to the build path while poking around Eclipse. By taking a look at the 'Configure Build Path...> Libraries I removed the culprit class and now only have the
JRE System Library
Maven Dependencies
and nothing is complaining.
In my case I tried all the tips suggested but the error remained. I solved changing with a more recent version and writing that in the pom.xml. After this everything is now ok.
I deleted the local maven repository.
Then just rightclick the project -> Maven -> Update Project...
Select all concerned projects and click OK.
I was facing the same problem with my project.
My project was not able to find this archive: -
C:\Users\rakeshnarang\.m2\repository\org\hibernate\hibernate-core\5.3.7.Final
I went to this directory and deleted this folder.
Went back to eclipse and hit ALT + F5 to update the project.
The jar file was downloaded again and the problem was solved.
You should try this.
This happens when Eclipse screws up. To fix it, delete all the files in:
workspace/.metadata/.plugins/org.eclipse.jdt.core
Remove maven dependenices from build path
I faced this problem. I had "Archive for required library spring-boot-devtools cannot be read or is not a valid ZIP file" and the solution was like that:-
1- determine the dependencies names that have problems(for may case it is spring-boot-devtools).
2- close eclipse.
3- search in your .m2 file on these dependencies(by name).
4- delete these folders.
5- reopen eclipse and let maven rebuild your dependencies again.
Ok, I had the same problem with STS on a mac and solved it by deleting all the files in repository folder and from the STS IDE click on the project and then Maven -> Update project. Give it a couple of minutes to download all the dependencies and the problem is solved.
I face with the same issue. I deleted the local repository and relaunched the ID. It worked fine .
Just had this problem on Indigo SR2. It popped up after I removed a superfluous jar from the classpath (build path). Restarting Eclipse didn't help. Added back the jar to the build path...error went away. Removed the jar once again, and this time I was spared from another complaint.
none of the solutions above helped my problem. I've resolved it by deleting all files in {projectworkspace}/.metadata folder AND in {location}/.m2 folder and let eclipse download every single thing again. Hope this helps someone, cheers!
When I got an error saying "archive for required library could not be read," I solved it by removing the JARS in question from the Build Path of the project, and then using "Add External Jars" to add them back in again (navigating to the same folder that they were in). Using the "Add Jars" button wouldn't work, and the error would still be there. But using "Add External Jars" worked.
This could be due to you have added spring-licence.txt file to your web app libraries.
I had similar issue and resolved after removing that text file. In libraries it will expect jar file only.
Alternatively, below commands also worked for me:
mvn -s settings.xml eclipse:clean
mvn -s settings.xml eclipse:eclipse
In case of VSCode, follow the below steps:
Navigate to the respective folder that contains the corrupted jar
Delete just the jar
mvn clean
mvn compile
That worked for me.
Read the issue in Problems section,identify which dependency not able to read, then go the maven repository .m2\repository ->
1)check the dependencies and delete it from the folder
2)go to STS/Eclipse -> click on maven -> update project ->select the force update of snapshots/releases and click on ok.
or
delete the dependencies from the .m2/repository and rebuild the maven --> update the maven project
In my case, I just had to remove the following 2 lines from proguard.cfg:
-keep class android.support.v4.** { * ; }
-dontwarn android.support.v4.**
Yes, I know that the question refers to the Spring Tool Suite but:
Spring Tool Suite is based on Eclipse (the IDE I am currently using for ADT).
Proguard is a Java obfuscator that can be used for any project, not just Android
I tried all the suggested answers and tips in the thread and none worked for me, until I removed the references to said libs.
I hope this helps someone.
Delete your C:\Users\PC\.m2** folder
and update maven project

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

Platform: IntelliJ Community Edition 10.0.3
SDK: jdk1.6.0_21
OS: Windows 7
So I have a strange situation with IntelliJ that has me completely stumped. I setup a Maven project and add log4j as a dependency in the pom.xml file. The IDEA inspections run fine and my unit tests all compile and run.
I then added hunnysoft's jmime library to my local maven repository using the mvn install:install-file as follows.
mvn install:install-file -Dfile=jmime.jar -DgroupId=jmime \
-DartifactId=jmime -Dversion=3.1.1e -Dpackaging=jar
Maven installed the jar file just fine into my local repository.
I then went into IntelliJ's Settings => Maven => Repository Services and Updated my local repository (so that IntelliJ would reindex the repository contents).
Finally, I added the following dependency to my pom.xml file (just above the log4j dependency).
<dependency>
<groupId>jmime</groupId>
<artifactId>jmime</artifactId>
<version>3.1.1e</version>
</dependency>
I now create a new class as follows:
package com.stackoverflow.question;
import org.apache.log4j.Logger;
import com.hunnysoft.jmime.ByteString;
import com.hunnysoft.jmime.Field;
import com.hunnysoft.jmime.FieldBody;
public class StackOverflowQuestion {
public Field create(String name, String text) {
Logger.getLogger(getClass()).debug("create entered");
FieldBody body = new FieldBody();
body.setText(new ByteString(text));
Field field = new Field();
field.setFieldName(name);
field.setFieldBody(body);
return field;
}
}
Now for the weirdness. IntelliJ's intention mechanism picks up and recognizes the Logger import in the maven pom file just fine. However, for all of the hunnysoft imports it reports: "Cannot resolve symbol 'ByteString/Field/FieldBody'", BUT Build => Compile 'StackOverflowQuestion.java' compiles everything correctly and the unit test I created for this class runs fine (though the intentions mark the call to create() as a problem area too).
So somewhere, somehow IntelliJ is ignoring the jmime.jar file for the intention subsystem. I'm confused because the log4j dependency works fine and everything compiles and runs fine. F12 ("Go To Declaration") works on the Logger import, but breaks on all the jmime imports.
Oh, one other thing, if I go to the 'Packages' view in the "Projects" window the "com.hunnysoft.jmime" package appears and I can see ALL of the classes I imported in the code snippet above under "Libraries". Removing the above dependency from the pom.xml file causes this package to disappear and the compilation breaks.
It appears that the inspection's classpath is broken, but there does not seem to be a setting for this anywhere in the Settings => Intentions | Compiler areas (not that I expected any such settings, I believe the IDEA should already know the correct classpath based on the pom file and JDK).
As a final experiment I created a brand new standard J2SE application project (without using maven) and added the jmime.jar file directly to the project as one of its libraries. I run into exactly the same problems as described above in this new project.
Here is the MANIFEST.MF from the jmime jar file.
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.5.4
Created-By: 10.0-b23 (Sun Microsystems Inc.)
Name: com/hunnysoft/jmime/
Sealed: true
Specification-Title: Hunny JMIME
Specification-Version: 3.1.1
Specification-Vendor: Hunny Software, Inc.
Implementation-Title: com.hunnysoft.jmime
Implementation-Version: 3.1.1E
Implementation-Vendor: Hunny Software, Inc.
I don't see anything unusual in this jar file.
My best guess is that perhaps the problem might be a missing dependency issue. But AFAIK jmime is supposed to be self contained (JarAnalyzer doesn't come up with anything, but I'm not sure it would if a dependency jar is missing).
So, anyone have any IDEAs?
First of all you should try File | Invalidate Caches and if it doesn't help, delete IDEA system directory. Then re-import the Maven project and see if it helps.
In some weird cases compiled classes may report wrong info and confuse IDEA. Verify that the classes from this jar report correct names using javap.
The following trick resolved this issue for me:
Right click on the code editor
Hover on Maven and expand
Click on Reimport
My idea version is 12.0.4
None of the solutions above worked for me. What did was removing the main.iml file manually and it suddenly worked.
This was mentioned in another answer to this same question here, but this alone fixes this for me. I do all my builds in a separate terminal, outside of IntelliJ. So the cache's need to have the proper permissions set for the IntelliJ app to read them.
Run it from the project's root folder.
$ mvn -U idea:idea
For Gradle users:
You may need to synchronize your project with your build.gradle file.
You can right-click on your gradle file under the Project pane to do this, but that didn't seem to do anything for me (I suspect a bug in my version). You'll know if this happens because it wont' kick off any IntelliJ tasks that you will be waiting on. Instead, open up the Gradle Tool pane, then click the synchronize (refresh) button. This worked for me where invalidating the cache and restarting did not.
My own circumstance: I was using a Scala project with Gradle and had to do this.
One extra step, when I did File -> Invalidate Caches and restarted the IDE, open a project. It popped up a toastbox on the top-right asking me whether to enable auto-import and that solved the problem.
Inconsistent/duplicate module names in project structure was causing this issue for me.
Go to File -> Project Strucutre -> Modules
In Click on modules which have red underline
Got to "Dependencies" tab
Make sure the dependencies which are red actually exist in dependency list. If not, rename them to match existing dependency names
This can happen when IntelliJ doesn't shut down properly and thus cannot properly save renamed module names.
Another thing to check: Be sure that dependencies are not duplicated. In my case I found that a module exhibiting this behavior was misconfigured as follows: it had a dependency on another module, and it had a dependency on a jar produced by that other module. This meant for every symbol referenced in duplicate, and was ambiguous.
Has a fixed been published? Appears issue originally affected v11/12 due to a "Compiler overhaul" back in 2013. With discussion on related issues in Jira up to end of 2014.
http://youtrack.jetbrains.com/issue/IDEA-98425
Also on Jira IDEA-98425 was marked fixed but unverified (on v12.0.3). None of the following work-around helped resolve this "Unable to Resolve Symbol" issue with Version 13.1.1 on Windows
a. Delete .IdealIC13 folder (Then, File \ Invalidate Caches / Restart)
b. From Maven Projects window,
b.1 mvn -U idea:idea –〉Executing this maven goal suppose to reload the dependencies. This works prev, but since last FRI, executing this maven goal failed as it tried to recompile the project (Of course it fails as "Unable to resolve Symbols", that's what I am trying to fix by running this command in the first place) mvn -version — shows maven version referenced 3.2.5 and that it's working
b.2 Simply right click project, and Reimport
b.3 File \ Invalidate Caches / Restart
c. Tried both Enable & Disable this setting: File -> Settings -> Maven -> Importing -> "Use maven3 to import project"
d. Settings \ Maven \ Multiproject build fail policy = Fail at end (instead of Default)
Nothing works. What's happenning to IntelliJ support on Maven.
https://youtrack.jetbrains.com/issue/IDEA-99302
From JetBeans release history, https://www.jetbrains.com/company/history.jsp
IntelliJ v14 NOV 2014
IntelliJ v13 DEC 2013
I'd assume v12 fixed (although unverified) would be incorporated in subsequent releases. Any one having similar problems with which IntelliJ version? Please share your experience. IntelliJ maven support seems broken.
Press "shift" two times > "Reimport All Maven projects" always works for me.
None of the other answeres worked for me. My imports were not being resolved because IntelliJ pointed to wrong .m2 file.
IntelliJ Version: IntelliJ Idea 2018.1.5
My location for the .m2 directory was pointed to the wrong path. All I did to fix it was re-point IntelliJ to the right .m2 directory and update it.
First, go to: File->Settings->Build, Execution, Deployment->Build Tools->Maven
I had to change the User settings file: and the Local repository: to the correct location of my .m2 directory.
After this go to: File->Settings->Build, Execution, Deployment->Build Tools->Maven->Repositories
and click the Update button.
I'm jealous of all of you who resolved through File / Invalidate caches. I just spent hours trying everything on this question and a few others from around the web.
The magic menu item didn't do it for me so I invalidated the caches myself by nuking %USERPROFILE%\AppData\Local\JetBrains\IntelliJIdea2020.3\caches
Once I did this and restarted IntelliJ (2020.3), the indexes were rebuilt and my errors went away.
My Project Structure:
src -> main -> scala -> mypackages
What worked:
Right click on the scala folder, and click "Mark Directory as Sources Root".
I had problem with Maven Importer JDK - somehow it switched itself to JDK 11, but Maven Project reload worked only with JDK 8.
Update 2022
IntelliJ 2022.1 has an interactive, step-by-step process File -> Repair IDE. It leads you through 5 steps in sequence to try and resolve this problem for the current project before invalidating the caches for all projects. From the IDEA documentation:
Refresh Project Indexes
Rescan Project Indexes
Reopen Project
Drop Shared Indexes
Reindex Project
Invalidate Caches and Restart
Steps 1- 3 fixed it for my project.
In v2022.3 and the new UI, this setting is now in File -> Cache Recovery -> Repair IDE. You can also select an individual step from there.
If your maven project is a multi-module project, check if some of the modules are ignored by intellij.
Click on View -> Tool Windows -> Maven Projects, and check if some modules are ignored(Ignored modules are in grey, e.g. gs-multi-module in the following image).
Right click on the ignored module and choose Unignore Projects.
Then wait for intellij to finish indexing, after which it will work.
For Gradle projects:
Exit IntelliJ IDEA
Delete the <problematic-project-root>/.idea directory
Delete the <problematic-project-root>/.gradle directory
Delete all .iml files in <problematic-project-root>
windows command prompt: DEL /S /Q *.iml
linux: find . | grep -e .iml$ | xargs rm
Re-import the project into IntelliJ IDEA with Gradle
In IntelliJ IDEA 2020.3, select:
File > Invalidate Caches / Restart... > Invalidate and Restart
When prompted with Download pre-built shared indexes:
don't import the shared indexes: close the dialog or choose More actions > Don't show again
Yes, sounds like you have to create libraries containing the JARs you need and add them as a dependency in your module.
For another alternative.
I got this problem also when I used JDK7_07. I tried all answers here (except deleting IDEA System Directory). But, I still got the problem. So what I did it is:
Install newest JDK (it was JDK7_45), and set the Intellij's JDK to the new one, and it works.
Re-importing the project worked for me.
Right Click on Project -> Maven ->Reimport
when I did File -> Invalidate Caches and restarted the IDE,open a project. It showed a dialogue on the top-right "Maven changes detected" and gave an option to import and enable auto-import. Even after importing the project here, I had the same issue. The above step solved the problem.
Suggested solutions did not work. I had to unignore several projects, by right clicking on the pom => maven => unignore project.
Then after a
mvn clean install -T 6 -DskipTests
in the console, IntelliJ was happy again. No idea how the projects became ignored...
Sometimes, I just open project structure, and click project, then choose a SDK version.
In my case, I am trying to open a spring boot project from IntellijIdea got the same issue like unable to import all spring related files.
Then I did:
File -> Close Project -> Import Project -> Import from external model -> Choose Gradle -> Next -> Select the project from file location -> Finish
Now everything working fine as expected.
I have seen many answers here but I finally found this solution. It may use for someone like me.
I just had this issue and it would just not go away. I eventually wiped out the IntelliJ config directory in ~ and rebuilt my IntelliJ project from scratch. (This only took about 15 minutes in the end, compared to spending an hour trying to work out problems with cached files, etc.)
Note that my guess is that the initial problem was caused by something like javathings.blogspot.com/2009/11/too-many-open-files-in-intellij-idea.html (NB: as of 2018, that link is dead, but archive.org has a copy of the page from around when this answer was first written -ed.) or a disk space/memory issue causing Java to crash. IntelliJ seemed to just get corrupted.
After invalidating my cache and restarting; and confirming my maven settings were okay, I was still seeing "Cannot resolve symbol" for a module that I definitely had set as a dependency. Turns out I had it set to the wrong scope.
You can check by right clicking on your module and selecting Open Module Settings. Click the dependency tab and verify that the scope for your un-resolvable dependency is set to Compile.
Open "Settings"
Search for "Maven"
Click on "Ignored Files" under "Maven"
Uncheck the pom.xml files contains the missing dependencies
Click "OK"
Click File -> Invalidate Caches/Restart...
Click "Invalidate and Restart"
mvn idea:idea worked for me. Found it here. Spent more than an hour, hope it helps someone
In my case, my project was using Lombok and I was missing the Lombok Plugin in IntelliJ. After installing it everything worked fine.
I tried
File -> Invalidate and Restart
which did not worked for me.
Solution that really worked :
Project Structure -> Modules -> select target folder -> Right click generated-sources and select sources -> Apply -> ok

Problem loading resources while running in Eclipse

I'm working on a swing project, using maven2 (from command-line) and eclipse (without maven integration). So, I generate the eclipse project through maven eclipse plugin (mvn eclipse:eclipse), import it inside eclipse, and do all my work.
My problem is: when I run my app in eclipse (as a Java Application), I can't find none of the resources that are in my src directory. Digging for information on my problem, I get into this answer from another question. So, I compared the output from the following instructions:
MyClass.class.getResource("/").getPath();
MyClass.class.getProtectionDomain().getCodeSource().getLocation().toString();
Those gave me the following outputs, respectively:
${workspace_loc}/${my_project}/target/test-classes/
file:/${workspace_loc}/${my_project}/target/classes/
Checking the above locations, I could see that the former is empty, while the other one contained all my compiled classes and resources. So, I came to the conclusion that the classloader is looking for my resources in the wrong place. So, I think I have three questions:
Is my understanding correct?
If so, how it does to find the classes it is loading?
How do I solve this?
UPDATE: I've changed my code, so instead of invoking MyClass.class.getResource(...) or MyClass.class.getResourceAsStream(...), I'm now using ClassLoader.getSystemResource(...) and ClassLoader.getSystemResourceAsStream(...). In this way, everything is working fine in eclipse. I just don't know exactly why. Any hint on this?
Two possibles cases for me :
You are using eclipse to compile your project. Then eclipse is configured to exclude (or not include) resources in the src folder. You can set it in Project/Properties/Java Build Path/Source. Then you expend your src folder, and ensure you have something like "Included All", "Excluded None".
You run your maven application using maven to compile and not eclipse, even though you are using eclipse as your IDE. Then by default maven will not copy resources from the source folder to the output folder... Because it is not the standard maven way of doing things. Thus the resource are missing from the classpath and you don't find them. Just change your maven configuration to also include resources from your source folder.
I think you have to add src/main/resources to the build path. This is done in Project Properties > Build Path > Source. Here is how the standard maven project looks:
In future when using Eclipse I suggest to use m2eclipse plugin and create project using it. This will automatically make sure that all these folders are in the build path.
Try this:
Run configurations... -> Classpath -> User Entries -> Advanced... -> Add Folders
Can you try loading the resources using below?
this.getClass().getClassLoader().getResourceAsStream(propertyFileName)
This might be useful information
Eclipse Maven plugin has its own Classpath Container that conflicts with generated class paths when enabled.
What I would suggest is stop using eclipse:eclipse (sorry - harsh I know). I used it for about 8 months, cant believe it took me that long, and used M2Eclipse. M2Eclipse is an eclipse plugin in which you do the following.
Enable Dependency Management.
Update Project Configuration
(In Eclipse) Project -> Build Project
(In Eclipse) Run Application
It may not seem it, but its a much easier and less frustrating way of doing it.
Before, with eclipse:eclipse. You would have to run it then hit refresh and hope that everything is configured - if you have a multi-module pom things can really go wrong.
For me the Files within the WEB-INF were not getting included. Hence I added them to Buildpath (Project -> Build Path -> Configure Build Path -> Add folder (project/src/main/webapp). This resolved the issue.

Categories

Resources