'Source code does not match the bytecode' use IDEA debug JdbcTemplate - java

When I debug the JdbcTemplate sourcecode use IDEA,the IDE tips me:'Source code does not match the bytecode'
Screenshot:
and i use mvn to manage my project;my maven pom config is:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.orm</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

This can also happen if you have multiple dependencies that themselves have different versions of the same dependency. This post on the JetBrains site shows how to enable the alternate source switcher in preferences.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206822215-what-does-Choose-Sources-do-and-how-can-I-undo-what-it-does-

Intellij gives a such warning when compiled code doesn't match the source code, i.e. you try to debug the code but it has changed and not rebuilt.
Make sure after you imported your code you didn't modify it. If you modify then first build/compile it before starting the debugger.
For example below code will cause this warning :-
public class HelloSO {
public static void main(String[] args) {
System.out.println("First time source code");
}
}
Now you compiled above class and start debugging it, everything works fine.
But after that you add one more print statement and try to put the debug point on that line without re-compile it, then in this case as byte code for new line is not generated, hence you will get same warning from IntelliJ.

After viewing the other similar questions and answers on this problem, none of which helped me. What solved the problem was simply adding a dependency. In my case I ran into this issue when I was attempting to debug org.springframework.web.servlet.DispatcherServlet. I finally noticed that IntelliJ could not find javax.servlet in my imports.
In my Maven project, I added
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0.1</version>
</dependency>
to my pom.xml which solved the problem.
Double check that all of your imports are being resolved.

You can try this
Open or move to 'Project Panel'
Scroll down and find your library
Left click on your library
Inside the context menu, select 'Open Library Settings'
Once there, check that the binaries and sources are associated:

For me this issue was arising because I'd made changes to my source code but had not yet deployed them to the target device. It still allowed me to set up the debugging which was confusing, but then gave me this error.
To fix:
Rebuild your project / module
Redeploy to your target device
Run the debugger
After rebuilding / redeploying, your debug and deployed code will match up and you shouldn't get any more errors! Just a matter of matching up the two binaries.

I had the same issue, too. The root reason is two different jar packages have some conflicts. So I solved it by removing one of the conflicting jar package.

I had a problem like yours today. I found that my IntelliJ was set to work with Java version 16 and my project was built in Java version 11.
To fix it, I did this: clicked on File -> Project Structure -> Project Settings -> Project, and changed "Project SDK" property to version 11.
After clicking on OK button, I didn't get the message "source code does not match bytecode" anymore.

Related

When I start to use poi to print xls,an error happend. jaspersoft 6.17.0 and poi 5.2.2 [duplicate]

I'm getting a NoSuchMethodError error when running my Java program. What's wrong and how do I fix it?
Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it.
Look at the stack trace ... If the exception appears when calling a method on an object in a library, you are most likely using separate versions of the library when compiling and running. Make sure you have the right version both places.
If the exception appears when calling a method on objects instantiated by classes you made, then your build process seems to be faulty. Make sure the class files that you are actually running are updated when you compile.
I was having your problem, and this is how I fixed it. The following steps are a working way to add a library. I had done the first two steps right, but I hadn't done the last one by dragging the ".jar" file direct from the file system into the "lib" folder on my eclipse project. Additionally, I had to remove the previous version of the library from both the build path and the "lib" folder.
Step 1 - Add .jar to build path
Step 2 - Associate sources and javadocs (optional)
Step 3 - Actually drag .jar file into "lib" folder (not optional)
Note that in the case of reflection, you get an NoSuchMethodException, while with non-reflective code, you get NoSuchMethodError. I tend to go looking in very different places when confronted with one versus the other.
If you have access to change the JVM parameters, adding verbose output should allow you to see what classes are being loaded from which JAR files.
java -verbose:class <other args>
When your program is run, the JVM should dump to standard out information such as:
...
[Loaded junit.framework.Assert from file:/C:/Program%20Files/junit3.8.2/junit.jar]
...
If using Maven or another framework, and you get this error almost randomly, try a clean install like...
clean install
This is especially likely to work if you wrote the object and you know it has the method.
This is usually caused when using a build system like Apache Ant that only compiles java files when the java file is newer than the class file. If a method signature changes and classes were using the old version things may not be compiled correctly. The usual fix is to do a full rebuild (usually "ant clean" then "ant").
Sometimes this can also be caused when compiling against one version of a library but running against a different version.
I had the same error:
Exception in thread "main" java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonGenerator.writeStartObject(Ljava/lang/Object;)V
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:151)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3681)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3057)
To solve it I checked, firstly, Module Dependency Diagram (click in your POM the combination -> Ctrl+Alt+Shift+U or right click in your POM -> Maven -> Show dependencies) to understand where exactly was the conflict between libraries (Intelij IDEA). In my particular case, I had different versions of Jackson dependencies.
1) So, I added directly in my POM of the project explicitly the highest version - 2.8.7 of these two.
In properties:
<jackson.version>2.8.7</jackson.version>
And as dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
2) But also it can be solved using Dependency Exclusions.
By the same principle as below in example:
<dependency>
<groupId>group-a</groupId>
<artifactId>artifact-a</artifactId>
<version>1.0</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
Dependency with unwanted version will be excluded from your project.
This can also be the result of using reflection. If you have code that reflects on a class and extracts a method by name (eg: with Class.getDeclaredMethod("someMethodName", .....)) then any time that method name changes, such as during a refactor, you will need to remember to update the parameters to the reflection method to match the new method signature, or the getDeclaredMethod call will throw a NoSuchMethodException.
If this is the reason, then the stack trace should show the point that the reflection method is invoked, and you'll just need to update the parameters to match the actual method signature.
In my experience, this comes up occasionally when unit testing private methods/fields, and using a TestUtilities class to extract fields for test verification. (Generally with legacy code that wasn't designed with unit testing in mind.)
If you are writing a webapp, ensure that you don't have conflicting versions of a jar in your container's global library directory and also in your app. You may not necessarily know which jar is being used by the classloader.
e.g.
tomcat/common/lib
mywebapp/WEB-INF/lib
For me it happened because I changed argument type in function, from Object a, to String a. I could resolve it with clean and build again
In my case I had a multi module project and scenario was like com.xyz.TestClass was in module A and as well as in module B and module A was dependent on module B. So while creating a assembly jar I think only one version of class was retained if that doesn't have the invoked method then I was getting NoSuchMethodError runtime exception, but compilation was fine.
Related : https://reflectoring.io/nosuchmethod/
Why anybody doesn't mention dependency conflicts? This common problem can be related to included dependency jars with different versions.
Detailed explanation and solution: https://dzone.com/articles/solving-dependency-conflicts-in-maven
Short answer;
Add this maven dependency;
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<rules>
<dependencyConvergence />
</rules>
</configuration>
</plugin>
Then run this command;
mvn enforcer:enforce
Maybe this is the cause your the issue you faced.
It means the respective method is not present in the class:
If you are using jar then decompile and check if the respective version of jar have proper class.
Check if you have compiled proper class from your source.
I have just solved this error by restarting my Eclipse and run the applcation.
The reason for my case may because I replace my source files without closing my project or Eclipse.
Which caused different version of classes I was using.
Try this way: remove all .class files under your project directories (and, of course, all subdirectories). Rebuild.
Sometimes mvn clean (if you are using maven) does not clean .class files manually created by javac. And those old files contain old signatures, leading to NoSuchMethodError.
Just adding to existing answers. I was facing this issue with tomcat in eclipse. I had changed one class and did following steps,
Cleaned and built the project in eclpise
mvn clean install
Restarted tomcat
Still I was facing same error. Then I cleaned tomcat, cleaned tomcat working directory and restarted server and my issue is gone. Hope this helps someone
These problems are caused by the use of the same object at the same two classes.
Objects used does not contain new method has been added that the new object class contains.
ex:
filenotnull=/DayMoreConfig.conf
16-07-2015 05:02:10:ussdgw-1: Open TCP/IP connection to SMSC: 10.149.96.66 at 2775
16-07-2015 05:02:10:ussdgw-1: Bind request: (bindreq: (pdu: 0 9 0 [1]) 900 900 GEN 52 (addrrang: 0 0 2000) )
Exception in thread "main" java.lang.NoSuchMethodError: gateway.smpp.PDUEventListener.<init>(Lgateway/smpp/USSDClient;)V
at gateway.smpp.USSDClient.bind(USSDClient.java:139)
at gateway.USSDGW.initSmppConnection(USSDGW.java:274)
at gateway.USSDGW.<init>(USSDGW.java:184)
at com.vinaphone.app.ttn.USSDDayMore.main(USSDDayMore.java:40)
-bash-3.00$
These problems are caused by the concomitant 02 similar class (1 in src, 1 in jar file here is gateway.jar)
To answer the original question. According to java docs here:
"NoSuchMethodError" Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
If it happens in the run time, check the class containing the method is in class path.
Check if you have added new version of JAR and the method is compatible.
I fixed this problem in Eclipse by renaming a Junit test file.
In my Eclipse work space I have an App project and a Test project.
The Test project has the App project as a required project on the build path.
Started getting the NoSuchMethodError.
Then I realized the class in the Test project had the same name as the class in the App project.
App/
src/
com.example/
Projection.java
Test/
src/
com.example/
Projection.java
After renaming the Test to the correct name "ProjectionTest.java" the exception went away.
NoSuchMethodError : I have spend couple of hours fixing this issue, finally fixed it by just renaming package name , clean and build ... Try clean build first if it doesn't works try renaming the class name or package name and clean build...it should be fixed. Good luck.
I ran into a similar problem when I was changing method signatures in my application.
Cleaning and rebuilding my project resolved the "NoSuchMethodError".
Above answer explains very well ..just to add one thing
If you are using using eclipse use ctrl+shift+T and enter package structure of class (e.g. : gateway.smpp.PDUEventListener ), you will find all jars/projects where it's present. Remove unnecessary jars from classpath or add above in class path. Now it will pick up correct one.
I ran into similar issue.
Caused by: java.lang.NoSuchMethodError: com.abc.Employee.getEmpId()I
Finally I identified the root cause was changing the data type of variable.
Employee.java --> Contains the variable (EmpId) whose Data Type has been changed from int to String.
ReportGeneration.java --> Retrieves the value using the getter, getEmpId().
We are supposed to rebundle the jar by including only the modified classes. As there was no change in ReportGeneration.java I was only including the Employee.class in Jar file. I had to include the ReportGeneration.class file in the jar to solve the issue.
I've had the same problem. This is also caused when there is an ambiguity in classes. My program was trying to invoke a method which was present in two JAR files present in the same location / class path. Delete one JAR file or execute your code such that only one JAR file is used. Check that you are not using same JAR or different versions of the same JAR that contain the same class.
DISP_E_EXCEPTION [step] [] [Z-JAVA-105 Java exception java.lang.NoSuchMethodError(com.example.yourmethod)]
Most of the times java.lang.NoSuchMethodError is caught be compiler but sometimes it can occur at runtime. If this error occurs at runtime then the only reason could be the change in the class structure that made it incompatible.
Best Explanation: https://www.journaldev.com/14538/java-lang-nosuchmethoderror
I've encountered this error too.
My problem was that I've changed a method's signature, something like
void invest(Currency money){...}
into
void invest(Euro money){...}
This method was invoked from a context similar to
public static void main(String args[]) {
Bank myBank = new Bank();
Euro capital = new Euro();
myBank.invest(capital);
}
The compiler was silent with regard to warnings/ errors, as capital is both Currency as well as Euro.
The problem appeared due to the fact that I only compiled the class in which the method was defined - Bank, but not the class from which the method is being called from, which contains the main() method.
This issue is not something you might encounter too often, as most frequently the project is rebuilt mannually or a Build action is triggered automatically, instead of just compiling the one modified class.
My usecase was that I generated a .jar file which was to be used as a hotfix, that did not contain the App.class as this was not modified. It made sense to me not to include it as I kept the initial argument's base class trough inheritance.
The thing is, when you compile a class, the resulting bytecode is kind of static, in other words, it's a hard-reference.
The original disassembled bytecode (generated with the javap tool) looks like this:
#7 = Methodref #2.#22 // Bank.invest:(LCurrency;)V
After the ClassLoader loads the new compiled Bank.class, it will not find such a method, it appears as if it was removed and not changed, thus the named error.
Hope this helps.
The problem in my case was having two versions of the same library in the build path. The older version of the library didn't have the function, and newer one did.
I had a similar problem with my Gradle Project using Intelij.
I solved it by deleting the .gradle (see screenshot below) Package and rebuilding the Project.
.gradle Package
I had faced the same issue. I changed the return type of one method and ran the test code of that one class. That is when I faced this NoSuchMethodError. As a solution, I ran the maven builds on the entire repository once, before running the test code again. The issue got resolved in the next single test run.
One such instance where this error occurs:
I happened to make a silly mistake of accessing private static member variables in a non static method. Changing the method to static solved the problem.

Adding spock to eclipse without maven: General error during semantic analysis

I am trying to do my first test-automation with Spock.
I do not want to use maven.
I am using eclipse java EE oxygen 4.7.
I have created a groovy project.
I have added the Spock jar as an external library in the build path configuration.
Spock ist Spock-core-1.1-groovy-2.4.
I have also added geb jar the same way.
However, I am getting this strange error from the automatic build, which I do not understand and I am seeking for help. So far I haven't found anything helpfull.
General error during semantic analysis: Transform org.spockframework.compiler.SpockTransform#xxxx cannot be run org.codehaus.groovy.GroovyException:
Transform org.spockframework.compiler.SpockTransform#xxxx cannot be run at
org.codehaus.groovy.transform.ASTTransformationVisitor$3.call(ASTTransformationVisitor.java:416) at
org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:972) at
org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:633) at
org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:609) at
org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:586) at
org.codehaus.jdt.groovy.internal.compiler.ast.GroovyCompilationUnitDeclaration.processToPhase(GroovyCompilationUnitDeclaration.java:217) at
org.codehaus.jdt.groovy.internal.compiler.ast.GroovyCompilationUnitDeclaration.resolve(GroovyCompilationUnitDeclaration.java:613) at
org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:879) at org.eclipse.jdt.internal.compiler.ProcessTaskManager.run(ProcessTaskManager.java:141) at
java.lang.Thread.run(Unknown Source) Caused by: java.lang.NoClassDefFoundError: Unable to load class org.spockframework.runtime.ErrorCollector due to
missing dependency org/junit/runners/model/MultipleFailureException at org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:397) at
org.codehaus.groovy.ast.ClassNode.lazyClassInit(ClassNode.java:353) at org.codehaus.groovy.ast.ClassNode.getDeclaredMethods(ClassNode.java:981) at
org.codehaus.groovy.ast.ImmutableClassNode.getDeclaredMethods(ImmutableClassNode.java:105) at
org.spockframework.compiler.AstNodeCache.(AstNodeCache.java:65) at org.spockframework.compiler.SpockTransform$Impl.(SpockTransform.java:
52) at org.spockframework.compiler.SpockTransform.visit(SpockTransform.java:47) at
org.codehaus.groovy.transform.ASTTransformationVisitor$3.call(ASTTransformationVisitor.java:395) ... 9 more
My code is as simple as you can get. This is the code:
//The error is on the "p" letter of package
package hellowworld
class HelloWorld{
static main(args) {
}
}
Please note that this error only happens when I add Spock jar. The closest question was Spock without maven or gradle, but obviously the problems are different.
I just cut the file from the package directory pasted it out side and then recut pasted in the package back. It worked well and I have no idea why.
This is one of those problems which occasionally arise in Eclipse and most people just won't know why!
The thing to do usually is to try several "strategies" and hope that one will work. If not you have to come back to SO and try to enlist the support of an expert.
One tip: in my experience sometimes it is worth trying "Refresh Gradle" and "Build all" more than once. Not only that, but sometimes trying either of these actually then seems to do nothing... but a couple of seconds later the horrid x in the red box then vanishes like morning mist!
Highlight/select the project in Project Explorer --> right-click --> Gradle --> Refresh Gradle Project
Put cursor in a code file open in the editor, press Ctrl-B (Project --> Build all)
Close all files in editor, close Eclipse and start up Eclipse again
Try the above in various combinations
Reboot and then try the above in various combinations
If this fails to cure it you may need to turn to SO.

Testing Java code with Groovy under Intellij: unable to resolve class GroovyTestCase

I need to write a short test for some Java code. I used CTRL+SHIFT+T to generate one with IntelliJ, and selected "Groovy JUnit" as the testing library, then wrote the following test:
package util
class FibonacciHeapTest extends GroovyTestCase {
FibonacciHeap<Integer> heap
void setUp() {
super.setUp()
heap = new FibonacciHeap<>()
}
void testAddInOrder() {
testForItems 1..1000
}
private void testForItems(Range<Integer> items) {
items.each {heap << it}
assertEquals heap.size, items.to
items.each {assertEquals heap.remove(), it}
}
}
However, when I right click on the test case in the project window, I don't get the "Run All Tests" option that I normally do with JUnit tests, and the compiler throws the following error:
Information:2/4/15 8:15 PM - Compilation completed with 2 errors and 0 warnings in 2 sec
/home/patrick/IdeaProjects/hackerrank/src/test/java/util/FibonacciHeapTest.groovy
Error:(3, 1) Groovyc: unable to resolve class util.FibonacciHeap
Error:(9, 1) Groovyc: unable to resolve class GroovyTestCase
Trying to import GroovyTestCase or FibonacciHeap manually causes the same error. IntelliJ does not add any import statements when I let autocomplete finish the names for me, like it usually would with Java code.
What am I doing wrong?
This worked for me :
Open Gradle window (on right side in my case)
Click on refresh button
Done
I had a similar problem with creating test classes in IntelliJ, and it was solved when creating a new directory outside of the com.company folder (where I had the class I wanted to test).
Create a new directory for the test classes on the same level as your src folder
Right click on your new test directory, and "Mark directory as" --> "Test Resources Root"
Now create a test class, which should automatically be added to your test directory.
Build -> Rebuild project in the IDE itself (as opposed to maven, in my case) did it for me.
In my case, what I did to resolve the issue was rather simple.
Close IntelliJ
Open the attached homepage...
Remove your project by clicking on the x then...
Click on Import Project, Navigate to the build.graddle file of your project and open.
That was it and all the Red highlightings disappeared.
maybe you need add groovy-all rather then groovy,such as :
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy.version}</version>
</dependency>
You have to configure Groovy SDK first. See the screenshot
More detailed description in the official document: Configuring Global, Project and Module SDKs
As #sman591 pointed out in a comment, if you are getting the error:
groovyc: unable to resolve class groovy.util.GroovyTestCase
and you already have groovy as a dependency then you are probably just missing the junit dependency.
In IntelliJ IDEA I re-imported the project. It worked then.
I closed idea. I removed .idea folder in the project. And I imported the project.
Then I needed to set up Groovy, see previous answers, mark test directory as test source in all modules of my project.
I was selecting the root folder which had build.gradle file in it, but it didn't work.
Steps followed are similar to #Pila
close the project from intellij
remove .idea, log, out folders
go to intellij dashboard
import project from existing resources
select build.gradle file <-- this is important
now you should see all the tasks are getting build in the background, and once build is finished all red lines are gone.

Eclipse error ... cannot be resolved to a type

I have a dynamic web project that I am working on to migrate a jsp/servlet app from JRun to Tomcat.
I am getting the error: com.ibm.ivj.eab.dab.DatastoreJDBC cannot be resolved to a type.
I have the *.class files sitting inside a com/ibm/ivj/eab/dab folder (exactly how I found them). I have tried creating a jar file and adding that to the build path via "Add External Jar", I have also tried adding an "External Class Folder" and pointing to the folder that contains the "com" directory in question.
Still, the error persists. What is strange is if I start typing the package name eclipse actually auto-completes the class for me! (pictured below). Any ideas would be greatly appreciated. Maybe the classes were compiled for a much older java version and that is causing trouble? Maybe there is something I need to do to ensure the classes end up in the WEB-INF/lib directory?
I
Also If you are using mavenised project then try to update your project by clicking Alt+F5.
Or right click on the application and go to maven /update project.
It builds all your components and resolves if any import error is there.
Right click your project name.
Click Properties.
Click Java Build Path.
Click on Add Class Folder.
Then choose your class.
Alternatively, Add Jars should work although you claim that you attempted that.
Also, "have you tried turning it off and back on again"? (Restart Eclipse).
To solve the error "...cannot be resolved to a type.." do the followings:
Right click on the class and select "Build Path-->Exclude"
Again right click on the class and select "Build Path-->Include"
It works for me.
There are two ways to solve the issue "cannot be resolved to a type
":
For non maven project, add jars manually in a folder and add it in java build path. This would solve the compilation errors.
For maven project, right click on the project and go to maven -> update project. Select all the projects where you are getting compilation errors and also check "Force update of snapshots/releases". This will update the project and fix the compilation errors.
Project -> Clean
can at least sometimes be sufficient to resolve the matter.
For maven users:
Right click on the project
Maven
Update Project
Easy Solution:
Go to
Project property -> java builder path -> maven -> find c3p0-0.9.5.2.jar
and see the location where the file is stored in the local repository and go to this location and delete the repository manually.
Right click Project > Properties
Java Build Path > Add Class Folder
Select the bin folder
Click ok
Switch Order and Export tab
Select the newly added bin path move UP
Click Apply button
Solved the problem by dropping the jar into WEB_INF/lib.
copying the jar files will resolve. If by any chance you are copying the code from any tutorials, make sure the class names are spelled in correct case...for example i copied a code from one of the tutorials which had solr in S cap. Eclipse was continiously throwing the error and i also did a bit of googling ...everything was ok and it took 30 mins for me to realise the cap small issue. Am sure this will help someone
For many new users don't forget to add an asterisk (*) after your import statements if you wanna use all the classes in a package....for example
import java.io.*;
public class Learning
{
public static void main(String[] args)
{
BufferedInputStream sd = new BufferedInputStream(System.in);
// no error
}
}
================================================================
import java.io;
public class Learning
{
public static void main(String[] args)
{
BufferedInputStream sd = new BufferedInputStream(System.in);
// BufferedInputStream cannot be resolved to a type error
}
}
Solution :
1.Project -> Build Path -> Configure Build Path
2.Select Java Build path on the left menu, and select "Source"
3.Under Project select Include(All) and click OK
Cause :
The issue might because u might have deleted the CLASS files or dependencies on the project
Project -> Build Path -> Configure Build Path
Select Java Build path on the left menu, and select "Source"
click on Excluded and then Include(All) and then click OK
Cause : The issue might because u might have deleted the CLASS files
or dependencies on the project
For maven users:
Right click on the project
Maven
Update Project
First you need to update the pom.xml by adding below
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
1] Right click your project name.
2] Click Properties.
3] Click Java Build Path.
4] Check on 'Maven Dependencies' in Order and Export tabl.
In my case, previously it was not enabled. So when I enabled it my #GetMapping annotation works fine..
Also, there is the solution for IvyDE users. Right click on project -> Ivy -> resolve
It's necessary to set ivy.mirror property in build.properties
I just closed all the files and reopened them, and voila!!! Hope this helps someone in the future ;)
Download servlet-api.jar file and paste it in WEB-INF folder it will work

Error: Could not find or load main class in intelliJ IDE

I'm a beginner in Java and am trying to run my code using IntelliJ that I just installed as my IDE with JDK 1.7. The following piece of code keeps does not even compile and keeps giving me the error:
Error: Could not find or load main class libTest
Code
import java.lang.Integer;
import java.lang.String;
import java.lang.System;
import java.util.*;
class book {
private String name = "trial";
private int bookCode=1;
private int issued=0;
public void Issue(){
if(issued==0) {
issued=1;
System.out.println("You have succesfully issued the book");
}
else {
System.out.println("The book is already issued. Please contact the librarian for further details");
}
}
public int checkCode() {
return bookCode;
}
String readName() {
return name;
}
public void setName(String newName){
name=newName;
}
public void setBookCode(int newCode){
bookCode=newCode;
}
}
class library {
private ArrayList books=new ArrayList();
public void getList(){
for(int bk:books){
String bName=books(bk).readName();
System.out.println((bk+1)+") "+bName);
}
}
}
public class libTest{
public static void main(String[] args){
library newLib= new library();
System.out.println("code working");
}
}
Is there any change that i have to make in the compiler settings?? Or is it the code.
This might help:
1) "Build" menu -> "Rebuild Project".
Sometimes Intellij doesn't rewrite the classes because they already exist, this way you ask Intellij to rewrite everything.
2) "Run" menu -> "Edit configuration" -> delete the profile -> add back the profile ("Application" if it's a Java application), choose your main class from the "Main Class" dropdown menu.
3)"Build" menu -> "Rebuild Project".
If none of the above answers worked for you, just close your IntelliJ IDE and remove the IntelliJ IDE file and folder from the root of your project:
rm -rf .idea *.iml
Then open the project with IntelliJ. It must work now.
For me the solution was to fix the output directory under project settings. Before I was using just "target" for the Project compiler output. Instead I updated it to have a full path e.g. D:\dev\sigplusjava2_68\target
I had this problem and I tried everything under the sun that I could think of and on this site.
None of my Java classes were being picked up after I pulled from a remote branch. All the classes had red Js by their names in the Project Hierarchy, not blue Cs.
In the end, I tried to follow this tutorial and a few steps in tried something not described and fixed the issue:
https://www.jetbrains.com/help/idea/creating-and-managing-modules.html
Here's what I did:
Goto File | Project Structure, or press Crtl+Shift+Alt+S
Select Modules under the Project Settings section.
In the Sources tab click Sources on the 'Mark as:' line.
Click the Apply button.
For some reason, all my classes then had blue C's.
Someone with a better understanding of how IntelliJ and/or IDE's might be able to explain the phenomenon, but all I know is now it can see all the classes and more importantly the main one, and run.
Invalidate cache and restart your IntelliJ, it worked for me.
Explicitly creating an out folder and then setting the output path to C:\Users\USERNAME\IdeaProjects\PROJECTNAME\out
seemed to work for me when just out, and expecting IntelliJ to make the folder wouldn't.
Also try having IntelliJ make you a new run configuration:
Find the previous one by clicking
then remove it
and hit okay.
Now, (IMPORTANT STEP) open the class containing your main method. This is probably easiest done by clicking on the class name in the left-hand side Project Pane.
Give 'er a Alt + Shift + F10 and you should get a
Now hit Enter!!
Tadah??
(Did it work?)
File > Project Structure > Modules > Mark "src" folder as sources.
This should fix the problem. Also check latest language is selected so that you don't have to change code or do any config changes.
I know this was asked a while ago, but I was just stumbling over this issue and thought my findings might help others. As pointed out, the error message is basically a result of the out folder. That's because, when you're trying to run the program, it compiles the code first, and puts the compiled result to the out location, and then it tries to load the compiled code from the out location. If the compiled code is not in the location expected, you'll get the error.
The point I'm particularly wanting to share is that some times, the code is not compiled (built), even though your run configuration specifies "Build" in the "Before launch" section of the configuration panel.
When can this happen?
One situation that can cause this to happen is if you're using modules and you manually delete the module out directory. For example, if I have a module named "foo", there should be a directory named foo under out/production. If you manually delete it, the build system may not know that it needs to be rebuilt.
Even worse, if you select Build | Build module 'foo', it still may not rebuild the module. If that's the case, you should select a file in the module, for example 'bar.java' and then select Build | Recompile 'bar.java'. Now the out directory out/production/foo should be restored.
Since IntelliJ typically knows about any changes going on, this surprised me, and took me a little time to figure out, so I thought I'd share.
Check your class module : I have encountered this problem with intellij :
I have a maven multi-module project, the problem is that i runing a class which not exist the module within the configuration, so my problem is fixed by setting the right module ("edit configuration" -> "use class of module")
may this help you
I had to mark the "src" folder as "Sources". After restarting IntelliJ and rebuilding the project I could run the project without further issues (see screenshot).
Edit: You can access the "Project Structure" tab via File->Project Structure or by pressing Ctrl+Shift+Alt+S.
I ran into this problem when my Java class was under src/main/kotlin. After I moved it to src/main/java, the problem was gone.
I have faced such problems when the class is in the default folder, i.e. when the class does not declare a package.
So I guess using a package statement (eg. package org.me.mypackage;) on top of the class should fix it.
Open Modules Tab (Press Ctrl+Shift+Alt+S). I had two modules under one project. I've solved the problem after removing the second redundant module (see screenshot).
After creating your project in intelliJ, try running the following command:
mvn package
I have tried all the hacks suggested here - to no avail. At the end I have simply created a new Maven application and manually copied into it - one by one - the pom.xml and the java files and resources. It all works now. I am new to IntelliJ and totally unimpressed but how easy it is to get it into an unstable state.
Invalidating cache didn't work.
I edited the main class java file with a dummy change and ran it. It worked.
In my case the problem seemed to be related to upgrading IntelliJ. When I did this I overwrote the files from the old IntelliJ with the files from the new IntelliJ (2017 community to 2018 community). After that all of my projects were broken. I tried everything in this thread and none of them worked. I tried upgrading gradle to the latest version (4 to 4.8) and that didn't work. The only thing that worked for me was deleting the entire IntelliJ folder and reinstalling it. All of my projects worked after that.
I have tried almost everything suggested in the answers here, but nothing worked for me.
After an hour of just trying to run my application, I noticed that my project's path included non-ASCII characters (Arabic characters). After I moved my project to a path with no non-ASCII characters, it executed just fine.
Goto File-> Invalidate Caches and Restart .
Else delete rm -rf .idea *.iml
and restart InteliJ
You can run the maven command on the pom.xml file in your project directory:
mvn clean install
For me - i tried few of the options above, did not work. Then i just renamed my Application class and that probably forced intelliJ to build a fresh jar and error message started to change. Then i renamed it back and it worked.
Mark the directory as a source directory. Opened via Ctrl+Shift+Alt+S
modules.xml with wrong content, I don't know what's matter with my IDEA.
I inherited a bunch of .JAVA files from elsewhere and couldn't figure out how to get them to work in any IDE. Ultimately I had to go to the command line where the Main.JAVA file was and run javac Main.java. This created a bunch of .CLASS files. The IDE's were then able to figure out what to do.
I got this error when using Scala/SBT. IntelliJ could not find the main class, even though everything was set up correctly.
My solution: delete the <user>/.sbt/<version>/plugins/target folder, then restart IntelliJ.
You probably would have specified a wrong package and the package hierarchy would not be right. Look below
The ide would highlight the wrong path in that case.
I'm using IntelliJ with Spring and my main class is wrapped in a JAR.
I had to mark the 'Include dependencies with "Provided" scope' in the Run/Debug configuration dialog
We are at File/Project Structure..
Answer might be:
Folder indicated as "content root" needs a child folder where the code is.
Plus find the button that marks code as excluded and not.
Not to be confused with tickbox that states excluded without telling in what phase and what**
Is it compiler exclude or runtime exclude? You are doomed to test and lot.
So no that tickbox but icons and colors.
As an idea we need to crack how it was originally thought to work. They never got it to work in first place and started add things in premature codaculation style.
It has been so many years and you cannot expect any improvement.
But as cure we can hack out some way to get it right every time.
Another thing you can check here is the actual command that is being passed to the JVM and make sure it looks OK. Scroll to the top of your Run console, it should be the first line.
Spaces in your Run Configuration VM Options field will malform the app startup command and can result in this error message
-DsomeArgument="arg with space must be quoted"
I am working with Kotlin but am guessing the problem is the same. I would start a project, create a single file and add main to it and the IDE couldn't find the main.
I tried the things in this list and none worked. I finally mentioned my frustration on one of the IntelliJ pages and was contacted. Of course, it worked fine for IntelliJ. After a couple of days back and forth, I noticed that the highlight function wasn't working and mentioned that. It turned out something was wrong with the IDE settings. I still don't know specifically what was wrong but the fix in my case was to reset the IDE settings. File->Manage IDE Settings->Restore Default settings.
After this, the green triangle start icon became visible to the left of my main function and things continued to work normally for subsequent projects.
Thanks to Konstantin at JetBrain's support for his patience.

Categories

Resources