Меню

The import cannot be resolved eclipse ошибка

I’m trying to work with Hibernate in Eclipse.
I’m creating a new simple project and I’ve downloaded a collegue project too, via CVS.
Both don’t work, while on my collegue’s Eclipse do.
The problem is that, for each import of an Hibernate class, Eclipse says:

The import org.hibernate cannot be resolved

But all Hibernate jars are in the build path, that is:

antlr-2.7.6.jar
cglib-2.2.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate3.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
slf4j-api-1.6.1.jar

asked Dec 1, 2010 at 9:30

bluish's user avatar

bluishbluish

25.6k27 gold badges119 silver badges177 bronze badges

7

Try cleaning your project by going to the following menu item:

Project > Clean...

If that doesn’t work, try removing the jars from the build path and adding them again.

answered Dec 1, 2010 at 9:39

dogbane's user avatar

dogbanedogbane

262k75 gold badges391 silver badges411 bronze badges

8

Obviously there are cases where there is a valid issue however Eclipse throws this error for no good reason sometimes. This is still (in v 2020-09) an old (2010) Eclipse bug that can be resolved by making a negligible change to the project settings.

touch .classpath

solves the issue, or go to Project > Properties > Java Build Path > Order and Export > make a meaningless order change > Apply. Changing the order back does not regress to the problem.

answered Jul 15, 2016 at 20:55

user1133275's user avatar

user1133275user1133275

2,58727 silver badges30 bronze badges

5

If is a Maven project, also click on Maven >> Update project… (F5)

Update Maven project

answered Dec 14, 2016 at 7:56

albertoiNET's user avatar

albertoiNETalbertoiNET

1,20024 silver badges32 bronze badges

1

Clean the project. And double-check the jars being really on the build path (with no errors). Also make sure there is nothing in the «Problems» view.

answered Dec 1, 2010 at 9:38

Bozho's user avatar

BozhoBozho

582k141 gold badges1052 silver badges1136 bronze badges

3

I found the problem. It was the hibernate3.jar. I don’t know why it was not well extracted from the .zip, maybe corrupt. A good way to check if jars are corrupt or not is navigating through their tree structure in «Project Explorer» in Eclipse: if you can’t expand a jar node probably it’s corrupt. I’ve seen that having corrupt packages it’s frequent when you drag and drop them to the «Project Explorer». Maybe it’s better to move and copy them in the OS environment! Thankyou all.

answered Dec 1, 2010 at 10:26

bluish's user avatar

bluishbluish

25.6k27 gold badges119 silver badges177 bronze badges

I solved it by removing the project (do not delete on the disk) and importing it again.

bluish's user avatar

bluish

25.6k27 gold badges119 silver badges177 bronze badges

answered May 28, 2015 at 7:46

SoldierShen 's user avatar

0

  1. clean project
    Project — > clean…
  2. Right click on project — >BuildPath — >Configure BuildPath — >Libraries tab — >

Double click on JRE SYSTEM LIBRARY — >Then select alternate JRE

answered Jan 22, 2018 at 12:18

Balkrushna Patil's user avatar

This has solved my issue.

1) clean project Project -> clean…

2) Right click on project -> BuildPath -> Configure BuildPath -> Libraries tab ->
Double click on JRE SYSTEM LIBRARY -> Then select alternate JRE

3) Click Save

4) Again go to your project in project explorer and right click to project -> BuildPath -> Configure BuildPath -> Libraries tab ->
Double click on JRE SYSTEM LIBRARY -> This time select «Execution Environment»

5) Apply

Nisarg's user avatar

Nisarg

1,6336 gold badges18 silver badges31 bronze badges

answered Aug 23, 2018 at 19:04

Atul Waghmare's user avatar

1

I had the problem, that the classpath was broken somehow.

So right click on the project in Package explorer > Plug-in tools > Update classpath… did it for me

bluish's user avatar

bluish

25.6k27 gold badges119 silver badges177 bronze badges

answered Jun 22, 2012 at 7:51

wuppi's user avatar

wuppiwuppi

1,00410 silver badges16 bronze badges

1

I resolved this issue by updating the project: right click on the Maven project, select Maven -> Update Project -> select checkbox Force Updates of Snapshots/Releases.

bluish's user avatar

bluish

25.6k27 gold badges119 silver badges177 bronze badges

answered Jul 26, 2019 at 8:41

Kalahasthi Satyanarayana's user avatar

Try adding JRE System Library in the build path of your project.

answered Jun 19, 2013 at 7:39

Gaurav Pant's user avatar

Gaurav PantGaurav Pant

3331 gold badge3 silver badges5 bronze badges

With me it helped changing the compiler compliance level.
For unknown reasons it was set to 1.6 and I changed it to 1.8.

Once at project level right click on project > Properties > Java Compiler, while in Eclipse click on menu Window > Preferences > Java > Compiler.

bluish's user avatar

bluish

25.6k27 gold badges119 silver badges177 bronze badges

answered Aug 1, 2017 at 12:46

Alex P.'s user avatar

Alex P.Alex P.

3,0013 gold badges21 silver badges32 bronze badges

1

I tried all of the answers above but no luck. In my case, there is a generated build/classes folder with some additional «.class» files. I ended up going to the package explorer, right-clicking on the project and selecting the «Refresh» option and that made the build/classes folder available again resolving the issue.

answered Feb 21, 2018 at 19:28

egallardo's user avatar

egallardoegallardo

1,2341 gold badge15 silver badges25 bronze badges

In my case it was a broken jar in the Maven repository. Delete jar files in repository and let Maven download them again.

When I ran mvn clean install from the command line, it ran fine, but Eclipse still could not compile the code. When I ran maven install in Eclipse then I saw that Maven complained about bad jar file. So I deleted it and ran maven install again. The problem was gone.

bluish's user avatar

bluish

25.6k27 gold badges119 silver badges177 bronze badges

answered Aug 24, 2018 at 9:28

Evgeny Shmulev's user avatar

In order to download non-existing jar file in your .m2 directory, you should run mvn clean install command for your project pom.xml. Then you should update the project dependencies by clicking Alt+F5. This works for me!

bluish's user avatar

bluish

25.6k27 gold badges119 silver badges177 bronze badges

answered Jan 15, 2019 at 10:46

ÖMER TAŞCI's user avatar

ÖMER TAŞCIÖMER TAŞCI

5185 silver badges9 bronze badges

Removing the «module-info.java» did resolve the issue for me!

This file was automatically generated and did appear in my hierarchy…

answered Apr 4, 2019 at 15:46

val_t's user avatar

val_tval_t

211 bronze badge

I had the same problem because I added a jar I created, where I had set the packaging base directory other than the base directory of the classes.
As a result the class e.g. java.util.List had to be imported as util.List although the suggested import was the first one.

Check the imported jars under referenced libraries to see that they are imported correctly

answered Oct 25, 2012 at 10:04

kon psych's user avatar

kon psychkon psych

6161 gold badge11 silver badges26 bronze badges

I didn’t understand the reasoning behind this but this solved the same problem I was facing. You may require these steps before executing steps mentioned in above solutions (Clean all projects and Build automatically).

right click project -> Properties -> Project Facets -> select Java -> Apply

answered Jul 8, 2016 at 16:26

avp's user avatar

avpavp

2,71228 silver badges33 bronze badges

Whenever you come across this problem just go to Project > Clean, then select Clean all projects. It should get resolved, otherwise try to delete those jars and add them again. Last thing would be to try restarting Eclipse.

bluish's user avatar

bluish

25.6k27 gold badges119 silver badges177 bronze badges

answered Dec 28, 2016 at 18:33

Srinivas Thammanaboina's user avatar

pom.xml

If it’s a Maven project, go to pom.xml and remove all the dependency jars. Save it. Project will automatically build.

Then add dependency jars again (you can do Ctrl+Z). Save it. Project will automatically build and you won’t see that error.

bluish's user avatar

bluish

25.6k27 gold badges119 silver badges177 bronze badges

answered Aug 28, 2019 at 6:39

sravan's user avatar

sravansravan

1311 gold badge1 silver badge7 bronze badges

Solution for Eclipse IDE

In my case I fixed it by correcting one of these two files that may be corrupt: .classpath or .project.

To repair any of the corrupted files, you can copy from another project that has both the .project file or .classpath file in question and is error-free. But be sure not to add additional settings that will not be used.

bluish's user avatar

bluish

25.6k27 gold badges119 silver badges177 bronze badges

answered Nov 25, 2019 at 14:08

Tavo's user avatar

Remove the dependency in your POM.XML and download the jar and add it in buildpath.

sometime -> maven will not reflect new changes and this might cause this kind of prob

answered Jan 30, 2020 at 13:50

Rajagopal K's user avatar

right-click src->new package: Rename the package that you want to import and create a new class with the package class name.
E.g if import net.proteanit.sql.DbUtils; show import error

then create a new package with the name net.proteanit.sql
and make class DbUtils;

package net.proteanit.sql;
public class DbUtils {

}

Suraj Rao's user avatar

Suraj Rao

29.3k11 gold badges96 silver badges103 bronze badges

answered Dec 5, 2021 at 4:09

Prachi Nanavati's user avatar

Please try and check whether all the libs are in place. I had the same issue. But I solved it by moving the lib folder and adding all the jars again in the build path.

bluish's user avatar

bluish

25.6k27 gold badges119 silver badges177 bronze badges

answered Mar 11, 2014 at 9:35

Ravikumar's user avatar

0

I got the same problem. I downloaded the jar and added it to the build path, but I didn’t notice that the extension was .jar.zip. I again converted it to .jar and added to the build path.

It solved my problem. It’s a very silly mistake but I wrote it here in case it could help someone.

bluish's user avatar

bluish

25.6k27 gold badges119 silver badges177 bronze badges

answered Sep 18, 2014 at 5:12

smali's user avatar

smalismali

4,6076 gold badges36 silver badges58 bronze badges

If you are working with Maven and have this problem, check the repository server (for example nexus server), if the artifact is there. Sometimes, they can change the name of the artifact and you try to get the artifact with its old name.

answered May 10, 2016 at 10:15

drJava's user avatar

drJavadrJava

6872 gold badges9 silver badges24 bronze badges

Resolved by linking the source. From the explorer right click on the project, select properties, select Java Build Path, select Source from tabs, press button «LinkSource». And specifying the folder to add to the project.

answered Jul 19, 2017 at 14:47

livelovelaugh's user avatar

I couldn’t import as well.
Took me some hours to figure out, that I tried to use a 1.6 bound library/jar, while I was trying to compile for 1.8.
When I switched my project also to use 1.6, the import issue has gone.
All error messages were leading into wrong directions.
Just in the source I found some limitations directing to 1.6 version.
And:
For example the .settings and .classpath (File-Search) -> org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
can give a hint, on such issues.

answered Oct 27, 2018 at 12:13

sqller's user avatar

I faced the same issue and I solved it by removing a jar which was added twice in two different dependencies on my pom.xml. Removing one of the dependency solved the issue.

answered Dec 20, 2018 at 18:20

Reema's user avatar

ReemaReema

5873 gold badges12 silver badges36 bronze badges

When you start to develop web application using Java, you may think to use Eclipse as the IDE. Assume that you have seen a good tutorial about Java servlet on the internet or read the chapter of a book discussing about web development using JSP.

You are now writing the first servlet by using the wizard provided by the IDE. However, as soon the template file is loaded on the source code editor, you encounter the infamous error “The import javax.servlet cannot be resolved” just like depicted in the figure below.

Servlet import error


This error is normal. Servlet library is not shipped by default in Eclipse. You also can’t find the library in JRE/JDK package you download. Instead, you will find it in the lib folder under Tomcat installation directory like depicted below.

Servlet API jar file

So, how can we resolve the error? The solution is apparently simple. We just need to add the servlet jar file into the build path. Based on the scope, we can achieve this using two methods; single project-wise and all projects-wise. Both methods will be explained immediately. You just need to pay attention that these methods were tested under the following system environment and steps in other environment may vary:

OS: Windows
Eclipse version: Eclipse 3.5 Ganymede
JDK version: JDK 1.6.0_14

In the first method, we add the servlet-api jar by right-clicking the project name and choose Properties option. After clicking, a new popup window will appear. Click the “Java Build Path” menu on the left followed by choosing “Libraries” tab. Subsequently, click “Add External JARs” button and point to servlet-api.jar in lib folder of Apache Tomcat installation directory. If you do all these steps correctly, you will notice that servlet-api.jar has been added into the libraries. Please check your result with the reference picture below.

Adding servlet API into project library

Click “OK” to complete the modification. After a glance, you will notice all imports errors have been disappeared.

The first method is good if you rarely work with servlet. If you yourself are a very busy developer who has to build numerous projects for your vast client base, it is considerably wise to apply the second method. In this method, we will add the servlet-api.jar into the JDK directory. After the modification, you will never encounter the error again as the servlet-api.jar will always be in the build path. This is different with the previous method which requires you to modify the project properties again if you create a new dynamic web project.

To execute the second method, follow the instructions below:
1. In Eclipse workbench, choose Window > Preferences
2. Choose Java > Installed JREs on the left menu
3. Focus on the JDK you want to modify, click “Edit”. A new popup will appear

Adding servlet API JAR file into universal build path

4. Click “Add External JARs” and point to servlet-api.jar in lib folder of Tomcat installation directory.

Adding Servlet API JAR file into universal build path-2

5. Click “Finish” to close the second popup and “OK” to complete the modification

After you do all the steps, all the servlet import errors in the source code editor will have vanished. You will also have discarded the import error for all projects which require the servlet functionalities.

⛔️ The import javax.servlet can’t be resolved

import java.servlet cannot be resolved error.png

import java.servlet cannot be resolved error.png

If you receive the above error message in your java files (servlet classes) while working with eclipse IDE then you are most probably missing the API servlet-api.jar file that is needed by your project.

How to resolve javax.servlet error!

  1. Make sure that you have installed Apache Tomcat Server and have configured it to run your Application.
  2. Right Click on your Project folder,
  3. Now click on Properties at the bottom
  4. Right-Click-on-Project-Folder-and-Select-Properties.png

    Right-Click-on-Project-Folder-and-Select-Properties.png

  5. Select Java Build Path on the right.
  6. Go to Library tab.
  7. Click on Add External Library.
  8. Now go to the location where Apache Tomcat has been installed (e.g. : c:apache-tomcat-7.0.101).
  9. Now go to lib directory and Select servlet-api jar file.
  10. Apply Changes (Save).
  11. Just Clean + Build your project.
  12. The errors must now get resolved.

Add-servlet-api-jar.png

Add-servlet-api-jar.png

Note: Alternatively, you just copy the servlet-api jar file to the lib folder of your project

package com.code2care.org;


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.IOException;

public class ServletError extends HttpServlet
{


  /**
   * HTTP doGet request.
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response) 
  throws ServletException, IOException
  {
   
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("");
    out.println("Resolving Servlet Jar exception");
    out.println("");
    out.println("

Get : This works!.

"); out.println(""); out.close(); } /** * HTTP doPost request. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println("Resolving Servlet Jar Exception"); out.println(""); out.println("

Post : This works!.

"); out.println(""); out.close(); } }

I’m trying to work with Hibernate in Eclipse.
I’m creating a new simple project and I’ve downloaded a collegue project too, via CVS.
Both don’t work, while on my collegue’s Eclipse do.
The problem is that, for each import of an Hibernate class, Eclipse says:

The import org.hibernate cannot be resolved

But all Hibernate jars are in the build path, that is:

antlr-2.7.6.jar
cglib-2.2.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate3.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
slf4j-api-1.6.1.jar

30 Answers

Try cleaning your project by going to the following menu item:

Project > Clean...

If that doesn’t work, try removing the jars from the build path and adding them again.

Obviously there are cases where there is a valid issue however Eclipse throws this error for no good reason sometimes. This is still (in v 2020-09) an old (2010) Eclipse bug that can be resolved by making a negligible change to the project settings.

touch .classpath

solves the issue, or go to Project > Properties > Java Build Path > Order and Export > make a meaningless order change > Apply. Changing the order back does not regress to the problem.

Clean the project. And double-check the jars being really on the build path (with no errors). Also make sure there is nothing in the «Problems» view.

If is a Maven project, also click on Maven >> Update project… (F5)

Update Maven project

I found the problem. It was the hibernate3.jar. I don’t know why it was not well extracted from the .zip, maybe corrupt. A good way to check if jars are corrupt or not is navigating through their tree structure in «Project Explorer» in Eclipse: if you can’t expand a jar node probably it’s corrupt. I’ve seen that having corrupt packages it’s frequent when you drag and drop them to the «Project Explorer». Maybe it’s better to move and copy them in the OS environment! Thankyou all.

I solved it by removing the project (do not delete on the disk) and importing it again.

  1. clean project
    Project — > clean…
  2. Right click on project — >BuildPath — >Configure BuildPath — >Libraries tab — >

Double click on JRE SYSTEM LIBRARY — >Then select alternate JRE

This has solved my issue.

1) clean project Project -> clean…

2) Right click on project -> BuildPath -> Configure BuildPath -> Libraries tab ->
Double click on JRE SYSTEM LIBRARY -> Then select alternate JRE

3) Click Save

4) Again go to your project in project explorer and right click to project -> BuildPath -> Configure BuildPath -> Libraries tab ->
Double click on JRE SYSTEM LIBRARY -> This time select «Execution Environment»

5) Apply

I had the problem, that the classpath was broken somehow.

So right click on the project in Package explorer > Plug-in tools > Update classpath… did it for me

I resolved this issue by updating the project: right click on the Maven project, select Maven -> Update Project -> select checkbox Force Updates of Snapshots/Releases.

Try adding JRE System Library in the build path of your project.

With me it helped changing the compiler compliance level.
For unknown reasons it was set to 1.6 and I changed it to 1.8.

Once at project level right click on project > Properties > Java Compiler, while in Eclipse click on menu Window > Preferences > Java > Compiler.

I tried all of the answers above but no luck. In my case, there is a generated build/classes folder with some additional «.class» files. I ended up going to the package explorer, right-clicking on the project and selecting the «Refresh» option and that made the build/classes folder available again resolving the issue.

In my case it was a broken jar in the Maven repository. Delete jar files in repository and let Maven download them again.

When I ran mvn clean install from the command line, it ran fine, but Eclipse still could not compile the code. When I ran maven install in Eclipse then I saw that Maven complained about bad jar file. So I deleted it and ran maven install again. The problem was gone.

In order to download non-existing jar file in your .m2 directory, you should run mvn clean install command for your project pom.xml. Then you should update the project dependencies by clicking Alt+F5. This works for me!

Removing the «module-info.java» did resolve the issue for me!

This file was automatically generated and did appear in my hierarchy…

I had the same problem because I added a jar I created, where I had set the packaging base directory other than the base directory of the classes.
As a result the class e.g. java.util.List had to be imported as util.List although the suggested import was the first one.

Check the imported jars under referenced libraries to see that they are imported correctly

I didn’t understand the reasoning behind this but this solved the same problem I was facing. You may require these steps before executing steps mentioned in above solutions (Clean all projects and Build automatically).

right click project -> Properties -> Project Facets -> select Java -> Apply

Whenever you come across this problem just go to Project > Clean, then select Clean all projects. It should get resolved, otherwise try to delete those jars and add them again. Last thing would be to try restarting Eclipse.

pom.xml

If it’s a Maven project, go to pom.xml and remove all the dependency jars. Save it. Project will automatically build.

Then add dependency jars again (you can do Ctrl+Z). Save it. Project will automatically build and you won’t see that error.

Solution for Eclipse IDE

In my case I fixed it by correcting one of these two files that may be corrupt: .classpath or .project.

To repair any of the corrupted files, you can copy from another project that has both the .project file or .classpath file in question and is error-free. But be sure not to add additional settings that will not be used.

Remove the dependency in your POM.XML and download the jar and add it in buildpath.

sometime -> maven will not reflect new changes and this might cause this kind of prob

Please try and check whether all the libs are in place. I had the same issue. But I solved it by moving the lib folder and adding all the jars again in the build path.

I got the same problem. I downloaded the jar and added it to the build path, but I didn’t notice that the extension was .jar.zip. I again converted it to .jar and added to the build path.

It solved my problem. It’s a very silly mistake but I wrote it here in case it could help someone.

If you are working with Maven and have this problem, check the repository server (for example nexus server), if the artifact is there. Sometimes, they can change the name of the artifact and you try to get the artifact with its old name.

Resolved by linking the source. From the explorer right click on the project, select properties, select Java Build Path, select Source from tabs, press button «LinkSource». And specifying the folder to add to the project.

I couldn’t import as well.
Took me some hours to figure out, that I tried to use a 1.6 bound library/jar, while I was trying to compile for 1.8.
When I switched my project also to use 1.6, the import issue has gone.
All error messages were leading into wrong directions.
Just in the source I found some limitations directing to 1.6 version.
And:
For example the .settings and .classpath (File-Search) -> org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
can give a hint, on such issues.

I faced the same issue and I solved it by removing a jar which was added twice in two different dependencies on my pom.xml. Removing one of the dependency solved the issue.

For me, it seemed I was adding the wrong level of the library’s folder.
I downloaded the Jericho HTML Parser, unzipped it into
eclipse-workspace/libraries/jericho-html-3.4/

Then when adding this as an external library folder, the trick was to navigate to that folder, highlight the «classes» folder and press Open. I had previously tried adding both the parent and various levels of subfolders and it didn’t work.

This is pretty much explained here, it says

You can also add a class folder, a directory containing Java class
files that are not in a JAR.

There are two lessons learnt here for me, apologies if these are off-topic:

  1. Read the instructions carefully — as in word-by-word!

  2. Do not give up — this it the first time I am adding a library, it took me around two hours to get it added.

[Code Igniter frame work] [Import library]

Try right-clicking on the project in a Project Explorer view, choose refresh. All error markers are gone surprisingly to my case.


I’m not good at Eclipse. I started using Android Studio to develop Android. But, it’s annoying to see red error markers hovering all the time whilst the whole project still works fine. It happened to me when I use composer to import library like this:

require __DIR__ . '/../../vendor/autoload.php';

use FirebaseJWTJWT;

  • #2

прописал gradlew genEclipseRuns

А gradlew setupDecompWorkspace?

  • #3

А gradlew setupDecompWorkspace?

Блин че это, в README mdk такого не было. Мне удалить проект из Eclipse, зайти в терминал в его папке и прописать это? И потом снова импортировать?

  • #4

в README mdk такого не было

Возможно, ты читал ридми для mdk новых версий майна, которым не требуется setupDecompWorkspace

Мне удалить проект из Eclipse, зайти в терминал в его папке и прописать это? И потом снова импортировать?

Попробуй

  • #5

Возможно, ты читал ридми для mdk новых версий майна, которым не требуется setupDecompWorkspace

Да нет, этот ридми лежал в mdk forge для майна 1.12.2
Вот выхлоп от gradlew setupDecompWorkspace:

To honour the JVM settings for this build a new JVM will be forked. Please consider using the daemon: The Gradle Daemon — Gradle User Manual.
Daemon will be stopped at the end of the build stopping after processing

New Dep: net.minecraftforge:forge:1.12.2-14.23.5.2854_mapped_snapshot_20171003-1.12

FAILURE: Build failed with an exception.

* What went wrong:
Task ‘setupDecompWorkspace’ not found in root project ‘forge-1.12.2-14.23.5.2854-mdk’.

* Try:
Run gradlew tasks to get a list of available tasks. Run with —stacktrace option to get the stack trace. Run with —info or —debug option to get more log output. Run with —scan to get full insights.

* Get more help at Gradle | Search for Help with Gradle

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use ‘—warning-mode all’ to show the individual deprecation warnings.
See Command-Line Interface — Gradle User Manual

BUILD FAILED in 31s

  • #6

Тогда попробуй gradlew build

  • #7

Тогда попробуй gradlew build

Да все так же

Перевел, написано в первой же строчке что не может отыскать net.*, где его этот пакет net взять то

Я пытаюсь работать с Hibernate в Eclipse. Я создаю новый простой проект, и я также загрузил проект коллеги через CVS. Оба не работают, в то время как на Eclipse моего коллеги работают. Проблема в том, что для каждого импорта класса Hibernate Eclipse говорит:

The import org.hibernate cannot be resolved

Но все банки Hibernate находятся в пути сборки, то есть:

antlr-2.7.6.jar
cglib-2.2.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate3.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
slf4j-api-1.6.1.jar

30 ответы

Попробуйте очистить свой проект, перейдя в следующий пункт меню:

Project > Clean...

Если это не сработает, попробуйте удалить банки из пути сборки и снова добавить их.

ответ дан 01 дек ’10, 09:12

Очевидно, что есть случаи, когда существует действительная проблема, однако Eclipse иногда выдает эту ошибку без уважительной причины. Это по-прежнему (в версии 2020-09) старая (2010 г.) ошибка Eclipse, которую можно устранить, внеся незначительные изменения в настройки проекта.

touch .classpath

решает проблему или перейдите в Проект> Свойства> Путь сборки Java> Порядок и экспорт> внесите бессмысленное изменение порядка> Применить. Изменение заказа обратно не приводит к возникновению проблемы.

ответ дан 14 дек ’20, 18:12

Очистите проект. И еще раз проверьте, действительно ли jar-файлы находятся на пути сборки (без ошибок). Также убедитесь, что в представлении «Проблемы» ничего нет.

ответ дан 01 дек ’10, 09:12

Если это проект Maven, также нажмите Специалист >> Обновить проект … (F5)

Обновить проект Maven

ответ дан 14 дек ’16, 07:12

Я нашел проблему. Это был hibernate3.jar. Я не знаю, почему он не был хорошо извлечен из .zip, может быть развращать. Хороший способ проверить, повреждены ли jar-файлы или нет, — это просмотреть их древовидную структуру в «Project Explorer» в Eclipse: если вы не можете развернуть узел jar, вероятно, он поврежден. Я видел, что при наличии поврежденных пакетов часто перетащить их в «Обозреватель проекта». Может лучше переместить и скопировать их в среде ОС! Спасибо вам всем.

ответ дан 14 дек ’10, 07:12

Решил, удалив проект (не удалять на диске) и снова импортировав.

ответ дан 28 мая ’15, 14:05

  1. чистый проект Проект -> чистый …
  2. Щелкните правой кнопкой мыши проект -> BuildPath -> Настроить BuildPath -> вкладка Библиотеки ->

Дважды щелкните СИСТЕМНАЯ БИБЛИОТЕКА JRE -> Затем выберите альтернативный JRE

Создан 22 янв.

Это решило мою проблему.

1) чистый проект Project -> чистый …

2) Щелкните правой кнопкой мыши проект -> BuildPath -> Настроить BuildPath -> вкладка Библиотеки -> Дважды щелкните СИСТЕМНУЮ БИБЛИОТЕКУ JRE -> Затем выберите альтернативный JRE

3) Нажмите «Сохранить».

4) Снова перейдите к своему проекту в проводнике проекта и щелкните правой кнопкой мыши проект -> BuildPath -> Настроить BuildPath -> вкладка Библиотеки -> Дважды щелкните СИСТЕМНУЮ БИБЛИОТЕКУ JRE -> На этот раз выберите «Среда выполнения»

5) Применить

ответ дан 23 авг.

У меня была проблема, что путь к классам был каким-то образом сломан.

Итак, щелкните правой кнопкой мыши проект в проводнике пакетов> Инструменты подключаемого модуля> Обновить путь к классам … сделал это за меня

Создан 22 июн.

Я решил эту проблему, обновив проект: щелкните правой кнопкой мыши проект Maven, выберите Maven -> Обновить проект -> установите флажок Force Updates of Snapshots / Releases.

Создан 26 июля ’19, 13:07

Попробуйте добавить системную библиотеку JRE в путь сборки вашего проекта.

Создан 19 июн.

Со мной это помогло изменение уровня соответствия компилятора. По неизвестным причинам он был установлен на 1.6, а я изменил его на 1.8.

На уровне проекта щелкните правой кнопкой мыши проект> Свойства> Компилятор Java, а в Eclipse щелкните меню Окно> Настройки> Java> Компилятор.

ответ дан 02 авг.

Я попробовал все ответы выше, но не повезло. В моем случае это сгенерированная папка build / classes с некоторыми дополнительными файлами «.class». В итоге я перешел в проводник пакетов, щелкнул проект правой кнопкой мыши и выбрал опцию «Обновить», что снова сделало доступной папку build / classes, решив проблему.

Создан 21 фев.

В моем случае это была сломанная банка в репозитории Maven. Удалите файлы jar в репозитории и позвольте Maven снова загрузить их.

Когда я побежал mvn clean install из командной строки он работал нормально, но Eclipse все еще не мог скомпилировать код. Когда я бежал maven install в Eclipse я увидел, что Maven жаловался на плохой файл jar. Я удалил его и запустил maven install опять таки. Проблема исчезла.

ответ дан 27 авг.

Чтобы загрузить несуществующий файл jar в каталог .m2, вы должны запустить mvn clean install команда для вашего проекта pom.xml. Затем вам следует обновить зависимости проекта, нажав Alt+F5. У меня это работает!

Создан 15 янв.

Удаление «module-info.java» действительно решило проблему для меня!

Этот файл был автоматически сгенерирован и действительно появился в моей иерархии …

ответ дан 04 апр.

У меня была та же проблема, потому что я добавил созданную мной банку, в которой я установил базовый каталог упаковки, отличный от базового каталога классов. В результате класс eg java.util.List должен был быть импортирован как util.List хотя предложенный импорт был первым.

Проверьте импортированные jar-файлы в ссылочных библиотеках, чтобы убедиться, что они импортированы правильно.

ответ дан 25 окт ’12, 11:10

Я не понимал причины этого, но это решило ту же проблему, с которой я столкнулся. Эти шаги могут потребоваться перед выполнением шагов, упомянутых в приведенных выше решениях (очистить все проекты и выполнить автоматическую сборку).

щелкните правой кнопкой мыши проект -> Свойства -> Фасеты проекта -> выберите Java -> Применить

Создан 08 июля ’16, 17:07

Всякий раз, когда вы сталкиваетесь с этой проблемой, просто перейдите в «Проект»> «Очистить», затем выберите «Очистить все проекты». Это должно быть разрешено, в противном случае попробуйте удалить эти банки и добавить их снова. Последнее, что нужно сделать, это попробовать перезапустить Eclipse.

Создан 02 янв.

пом.xml

Если это проект Maven, перейдите в pom.xml и удалите все jar-файлы зависимостей. Сохрани это. Проект будет построен автоматически.

Затем снова добавьте банки зависимостей (вы можете сделать Ctrl+Z). Сохрани это. Проект будет построен автоматически, и вы не увидите эту ошибку.

ответ дан 28 авг.

Решение для Eclipse IDE

В моем случае я исправил это, исправив один из этих двух файлов, которые могут быть повреждены: .classpath or .project.

Чтобы восстановить любой из поврежденных файлов, вы можете скопировать из другого проекта, в котором есть .project файл или .classpath файл, о котором идет речь, и не содержит ошибок. Но не забудьте добавить дополнительные настройки, которые не будут использоваться.

Создан 26 ноя.

Удалите зависимость в вашем POM.XML, загрузите банку и добавьте ее в путь сборки.

когда-нибудь -> maven не будет отражать новые изменения, и это может вызвать такого рода проблемы

Создан 30 янв.

Пожалуйста, попробуйте и проверьте, все ли библиотеки на месте. Я была такая же проблема. Но я решил это, переместив папку lib и снова добавив все банки в путь сборки.

ответ дан 11 мар ’14, в 13:03

У меня та же проблема. Я загрузил jar-файл и добавил его в путь сборки, но не заметил, что расширение было .jar.zip. Я снова преобразовал его в .jar и добавил в путь сборки.

Это решило мою проблему. Это очень глупая ошибка, но я написал ее здесь на случай, если она кому-то поможет.

Создан 18 сен.

Если вы работаете с Maven и у вас возникла эта проблема, проверьте сервер репозитория (например, сервер нексуса), есть ли там артефакт. Иногда они могут изменить имя артефакта, и вы попытаетесь получить артефакт с его старым именем.

ответ дан 10 мая ’16, 11:05

Решено путем ссылки на источник. В проводнике щелкните проект правой кнопкой мыши, выберите «Свойства», выберите «Путь сборки Java», выберите «Источник» на вкладках, нажмите кнопку «Источник ссылок». И указав папку, которую нужно добавить в проект.

Создан 19 июля ’17, 15:07

Я тоже не мог импортировать. Мне потребовалось несколько часов, чтобы понять, что я пытался использовать связанную библиотеку / банку 1.6, в то время как я пытался скомпилировать для 1.8. Когда я переключил свой проект на использование 1.6, проблема с импортом исчезла. Все сообщения об ошибках вели в неправильном направлении. Просто в исходниках я обнаружил некоторые ограничения, касающиеся версии 1.6. И: Например, .settings и .classpath (File-Search) -> org.eclipse.jdt.core.compiler.codegen.targetPlatform = 1.6 может дать подсказку по таким вопросам.

ответ дан 27 окт ’18, 13:10

Я столкнулся с той же проблемой, и я решил ее, удалив банку, которая была добавлена ​​дважды в двух разных зависимостях моего pom.xml. Удаление одной из зависимостей решило проблему.

ответ дан 20 дек ’18, 18:12

Мне показалось, что я добавляю не тот уровень папки библиотеки. Я скачал Парсер HTML Jericho, разархивировал его в
eclipse-workspace/libraries/jericho-html-3.4/

Затем при добавлении этой папки в качестве внешней библиотеки трюк состоял в том, чтобы перейти к этой папке, выделить папку «классы» и нажать «Открыть». Раньше я пробовал добавить как родительский, так и различные уровни вложенных папок, и это не сработало.

Это в значительной степени объяснено здесь, это говорит

Вы также можете добавить папка класса, каталог, содержащий файлы классов Java, которых нет в JAR.

Я извлек из этого два урока, извиняюсь, если они не по теме:

  1. Внимательно прочтите инструкцию — как дословно!

  2. Не сдавайтесь — это первый раз, когда я добавляю библиотеку, мне потребовалось около двух часов, чтобы добавить ее.

Создан 19 ноя.

[Воспламенитель кода фреймворк] [Библиотека импорта]

Пытаться щелчок правой кнопкой мыши по проекту в представлении Project Explorer выберите обновление. В моем случае на удивление исчезли все маркеры ошибок.


Я не очень хорошо разбираюсь в «Затмении». Я начал использовать Android Studio для разработки Android. Но раздражает видеть постоянно парящие красные маркеры ошибок, в то время как весь проект по-прежнему работает нормально. Это случилось со мной, когда я использую композитор для импорта библиотеки следующим образом:

require __DIR__ . '/../../vendor/autoload.php';

use FirebaseJWTJWT;

Создан 10 фев.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

java
eclipse
import
jar
buildpath

or задайте свой вопрос.

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

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

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

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Tiled texture cache set to 4000 mb ошибка
  • The hunter primal ошибка you can see the only