Cannot be resolved to a type ошибка java

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?

Ienter image description here

BuZZ-dEE's user avatar

BuZZ-dEE

5,87512 gold badges66 silver badges95 bronze badges

asked Apr 3, 2013 at 18:10

mikey's user avatar

3

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.

answered Oct 28, 2014 at 7:35

AKS's user avatar

AKSAKS

6906 silver badges7 bronze badges

6

  1. Right click your project name.

  2. Click Properties.

  3. Click Java Build Path.

  4. Click on Add Class Folder.

  5. 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).

Patrick Haugh's user avatar

answered Apr 3, 2013 at 18:16

KyleM's user avatar

KyleMKyleM

4,4358 gold badges46 silver badges78 bronze badges

7

To solve the error «…cannot be resolved to a type..» do the followings:

  1. Right click on the class and select «Build Path—>Exclude»
  2. Again right click on the class and select «Build Path—>Include»

It works for me.

answered Apr 21, 2016 at 10:51

Amit Kumar Das's user avatar

0

There are two ways to solve the issue «cannot be resolved to a type
«:

  1. For non maven project, add jars manually in a folder and add it in java build path. This would solve the compilation errors.
  2. 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.

answered May 3, 2018 at 6:37

Swati Gour's user avatar

Swati GourSwati Gour

911 silver badge4 bronze badges

1

Project -> Clean

can at least sometimes be sufficient to resolve the matter.

answered Mar 12, 2018 at 18:47

Jool's user avatar

JoolJool

1,69616 silver badges14 bronze badges

For maven users:

  • Right click on the project
  • Maven
  • Update Project

answered Mar 17, 2017 at 15:44

Paulo Rodrigues's user avatar

1

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.

G

Nicolás Alarcón Rapela's user avatar

answered Sep 17, 2018 at 21:38

Nazrul Islam Riad's user avatar

  • 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

enter image description here

answered Jul 28, 2017 at 18:43

Prashanth Sams's user avatar

Prashanth SamsPrashanth Sams

19.3k20 gold badges101 silver badges125 bronze badges

Solved the problem by dropping the jar into WEB_INF/lib.

answered Sep 8, 2016 at 15:09

Andreas L.'s user avatar

Andreas L.Andreas L.

2,77522 silver badges23 bronze badges

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

answered May 22, 2017 at 11:57

Harish Narayanan's user avatar

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
    }
}

answered Aug 18, 2017 at 10:38

Jamisco's user avatar

JamiscoJamisco

1,6133 gold badges13 silver badges17 bronze badges

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

answered Mar 20, 2018 at 14:20

sundersparks's user avatar

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

answered Jun 4, 2018 at 10:56

Devendra  Singraul's user avatar

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..

answered Nov 22, 2018 at 17:04

Annu's user avatar

AnnuAnnu

5324 gold badges8 silver badges22 bronze badges

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

answered Apr 3, 2019 at 11:02

andron's user avatar

andronandron

241 silver badge11 bronze badges

I just closed all the files and reopened them, and voila!!! Hope this helps someone in the future ;)

answered Jul 8, 2020 at 11:35

charlchad's user avatar

charlchadcharlchad

3,3511 gold badge16 silver badges9 bronze badges

Download servlet-api.jar file and paste it in WEB-INF folder it will work

answered Jan 6, 2021 at 6:41

Binson Selvin's user avatar

1

This is the error I’m getting:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:  
    TeamLeader cannot be resolved to a type

    at TeamLeadDemo.main(TeamLeadDemo.java:26)

This is my code:

import java.util.Scanner;

public class Employee {
    public String empName, empNumber, hireDate;    

    public class TeamLeadDemo {}

    public Employee(String empName, String empNumber, String hireDate) {
        this.setEmpName(empName);
        this.setEmpNumber(empNumber);
        this.setHireDate(hireDate);
    }

    public void setEmpName(String empName) {
         this.empName = empName;
    }
        public void setEmpNumber(String empNumber) {
         this.empNumber = empNumber;
    }
    public void setHireDate(String hireDate) {
         this.hireDate = hireDate;
    }
    public String getEmpName() {
        return empName;
    }
    public String getEmpNumber() {
        return empNumber;
    }
    public String getHireDate() {
        return hireDate;
    }

    public class ShiftSupervisor extends Employee {
        public double annualSalary, annualProduction;
        //constructor
        public ShiftSupervisor(String empName, String empNumber,
                               String hireDate, double annualSalary,
                               double annualProduction) {
            super(empName,empNumber, hireDate);
            this.setAnnualSalary(annualSalary);
            this.setAnnualProduction(annualProduction);
        }

        public double getAnnualSalary() {
            return annualSalary;
        }
        public double getAnnualProduction() {
            return annualProduction;
        }
        public void setAnnualSalary(double annualSalary) {
            this.annualSalary = annualSalary;
        }
        public void setAnnualProduction(double annualProduction) {
            this.annualProduction = annualProduction;
        }

        public String toString() {
            return "Name: "+ getEmpName() + "nEmpID: "+ getEmpNumber()
                   + "nHire Date: "+ getHireDate() + "nAnnual Salary: "
                   + annualSalary + "nProduction: "+ annualProduction;
        }

        public class employeeStart {
            public void main(String[] args) {
                String name, id, date;
                double sal, prod;

                //create scanner object
                Scanner keyboard = new Scanner(System.in);

                //inputting data
                System.out.println("Enter Name: ");
                name = keyboard.nextLine();
                System.out.println("Enter id: ");
                id = keyboard.nextLine();
                System.out.println("Enter Hire Date: ");
                date = keyboard.nextLine();
                System.out.println("Enter Annual: ");
                sal = keyboard.nextDouble();
                System.out.println("Enter production: ");
                prod = keyboard.nextDouble();

                //instantiating object
                ShiftSupervisor pw = new ShiftSupervisor(name, id, date, sal, prod);

                //outputting data
                System.out.println("Employee Details: n" + pw);
            }
        }
        public class TeamLeader {
            public double monthlyBonus;
            public int minTraining, trainingPresent;    

            public TeamLeader(double monthlyBonus, int minTraining, int trainingPresent) {
                this.setMonthlyBonus(monthlyBonus);
                this.setMinTraining(minTraining);
                this.addtrainingPresent(trainingPresent);                    
            }

            public void setMonthlyBonus(double monthlyBonus) {
                this.monthlyBonus = monthlyBonus;
            }
            public void setMinTraining(int minTraining) {
                this.minTraining = minTraining;
            }
            public void setTrainingPresent(int t) {
                trainingPresent = t;
            }
            public void addtrainingPresent(int hours) {
                trainingPresent += hours;
            }
            public double getMonthlyBonus() {
                return monthlyBonus;
            }
            public int getMinTraining() {
                return minTraining;
            }
            public int getTrainingPresent() {
                return trainingPresent;
            }
            public String toString() {
                return "Bonus: "+ getMonthlyBonus() + "nMinimum Training: "
                + getMinTraining() + "nAttendence: "+ getTrainingPresent();
            }
        }
    }
}

In addition, I declared this in a separate class:

import java.util.Scanner;

public class TeamLeadDemo extends Employee {
    public TeamLeadDemo(String empName, String empNumber, String hireDate) {
        super(empName, empNumber, hireDate);
        // TODO Auto-generated constructor stub
    }

public static void main(String[] args) {
    double sal;
    int min, atten;

    //create scanner object
    Scanner keyboard = new Scanner(System.in);

    //inputting data
    System.out.println("Enter minimum training: ");
    min = keyboard.nextInt();
    System.out.println("Enter id: ");
    atten = keyboard.nextInt();
    System.out.println("Enter Bonus: ");
    sal = keyboard.nextDouble();

    //instantiating object
    ShiftSupervisor pw = new TeamLeader(sal, min, atten);

    //outputting data
    System.out.println("Employee Details:n" + pw);

    }
}

What is causing this error and how might I resolve it?

EDIT: Indentation, whitespace, naming conventions and readability issues have been somewhat addressed.

Andresgoro

0 / 0 / 1

Регистрация: 24.10.2015

Сообщений: 27

1

27.08.2016, 09:49. Показов 10458. Ответов 1

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Проблема в том что в главном файле я не могу создать объект класса SampleServerClass. SV1 компилятор видит как неинициолизорованную переменную , а на строку SampleServerClass sv1 = new SampleServerClass выдаёт ошибку cannot be resolved to a type. Помогите друзья кодеры)

Java
1
2
3
4
5
6
7
8
9
10
import SampleServerClass.java.*;
 
 
class Main{
    public static void main(String[] args){
        SampleServerClass sv1 = new SampleServerClass;
        sv1.main(args);
    }
    
}

Вот код самого класса

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package SampleServerClass.java;
 
 
    import java.io.*;
    import java.net.*;
 
 public class SampleServerClass extends Thread
    {
        Socket s;
        int num;
 
        public static void main(String args[])
        {
            try
            {
                int i = 0; // счётчик подключений
 
                // привинтить сокет на локалхост, порт 3128
                ServerSocket server = new ServerSocket(3128, 0,
                        InetAddress.getByName("localhost"));
 
                System.out.println("server is started");
 
                // слушаем порт
                while(true)
                {
                    // ждём нового подключения, после чего запускаем обработку клиента
                    // в новый вычислительный поток и увеличиваем счётчик на единичку
                    new SampleServerClass(i, server.accept());
                    i++;
                }
            }
            catch(Exception e)
            {System.out.println("init error: "+e);} // вывод исключений
        }
 
        public SampleServerClass(int num, Socket s)
        {
            // копируем данные
            this.num = num;
            this.s = s;
 
            // и запускаем новый вычислительный поток (см. ф-ю run())
            setDaemon(true);
            setPriority(NORM_PRIORITY);
            start();
        }
 
        public void run()
        {
            try
            {
                // из сокета клиента берём поток входящих данных
                InputStream is = s.getInputStream();
                // и оттуда же - поток данных от сервера к клиенту
                OutputStream os = s.getOutputStream();
 
                // буффер данных в 64 килобайта
                byte buf[] = new byte[64*1024];
                // читаем 64кб от клиента, результат - кол-во реально принятых данных
                int r = is.read(buf);
 
                // создаём строку, содержащую полученную от клиента информацию
                String data = new String(buf, 0, r);
 
                // добавляем данные об адресе сокета:
                data = ""+num+": "+"n"+data;
 
                // выводим данные:
                os.write(data.getBytes());
 
                // завершаем соединение
                s.close();
            }
            catch(Exception e)
            {System.out.println("init error: "+e);} // вывод исключений
        }
    }



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

27.08.2016, 09:49

1

Welemir1

Автоматизируй это!

Эксперт Python

7138 / 4434 / 1185

Регистрация: 30.03.2015

Сообщений: 12,898

Записей в блоге: 29

30.08.2016, 19:43

2

у тебя нет конструктора по умолчанию и вместо

Java
1
SampleServerClass sv1 = new SampleServerClass; //а где скобки??? нужно new SampleServerClass ()

нужно

Java
1
SampleServerClass sv1 = new SampleServerClass(i, socket);

ты уверен что тебе нужен класс мейн (не метод)? может начать с задачек попроще?



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

30.08.2016, 19:43

Помогаю со студенческими работами здесь

Создать объект класса Щенок, используя классы Животное, Собака. Методы: вывести на консоль имя, подать голос, прыгать, б
Создать объект класса Щенок, используя классы Животное, Собака.
Методы: вывести на консоль имя,…

Создать объект, взяв имя его класса из переменной типа String?
Привет всем!

Братцы, подскажите, ато у самого не получается…

Есть ParentClass и несколько…

Создать объект класса Пианино, используя класс Клавиша. Методы: настроить, играть на пианино, нажимать клавишу
Помогите пожалуйста!!
Создать объект класса Пианино, используя класс Клавиша. Методы:настроить,…

Почему я не могу создать объект класса с параметрами, которые я считала из бинарного файла?
#include &lt;string&gt;
#include &lt;iostream&gt;
#include &lt;conio.h&gt;
#include &quot;windows.h&quot;
#include…

Создать обЪект класса , у которого в параметрах конструктора объект этого же класса
Вот код:
TOgmGraphicsClass = class of TOgmGraphicsBlock;
TOgmGraphicsBlock =…

Jsp Type cannot be resolved to a type
Всем привет!
Работаю под IntelliJIDEA 17.3. В приложении использую JSP, Hibernate.
Когда включаю…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

2

Details
Written by  
Last Updated on 28 June 2019   |   Print  Email

When creating a new Java Servlet in Eclipse IDE, you may encounter the following errors:

HttpServlet cannot be resolved to a type
HttpServletRequest cannot be resolved to a type
HttpServletResponse cannot be resolved to a type
ServletException cannot be resolved to a type
The import javax.servlet cannot be resolved
WebServlet cannot be resolved to a type

It looks something like this screenshot in Eclipse:

Error httpservlet cannot be resolved to a type

The reason is the Java Servlet API is missing in the project’s classpath. You can solve this problem by specifying a server runtime for the project, e.g. Apache Tomcat runtime – because a Java web server is a servlet container that implements the Servlet API.

In Eclipse, right click on the project, click Properties. In the project properties dialog, click Java Build Path, and click the button Add Library… as shown below:

Java Build Path in Eclipse

In the Add Library dialog appears, select Server Runtime:

Add Library in Eclipse

Click Next. In the next screen select Apache Tomcat and click Finish:

server library tomcat

If you don’t see any Apache Tomcat servers here, probably you haven’t installed Tomcat nor added to Eclipse. So follow this tutorial to add Tomcat in Eclipse.

Click Finish to close the Server Library dialog, and you will see the server library Apache Tomcat appears:

Apache Tomcat in Libraries

Then click Apply and Close, the errors will be gone.

In case you use Maven, the solution would be simpler. Just add a dependency for Java Servlet API in the pom.xml file like this:

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
	<version>3.0.1</version>
	<scope>provided</scope>
</dependency>

Save the file and wait for seconds for Maven to update the project. You will see the errors are gone way.

 

NOTE: To avoid this error in future, you should select the Target Runtime as Apache Tomcat when creating the project in Eclipse:

Target Runtime Apache Tomcat

 

Other Java Servlet Tutorials:

  • Java Servlet for beginners (XML)
  • Java Servlet for beginners (Annotation)
  • Java Servlet and JSP Hello World Tutorial with Eclipse, Maven and Apache Tomcat
  • How to use Session in Java web application
  • How to use Cookies in Java web application
  • Java File Upload Example with Servlet
  • Java File Download Servlet Example

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Возможно, вам также будет интересно:

  • Cannot assign without a target object ошибка
  • Cannot add or update a child row a foreign key constraint fails ошибка
  • Cannot access before initialization js ошибка
  • Canister purge solenoid valve circuit ошибка рено
  • Candy сушильная машина ошибка e14

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

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