简体   繁体   English

如何在Java中的相同程序包和相同目录中调用类?

[英]How to Call a class within same package and same directory in java?

Basically I have: 基本上我有:

package duck.reg.pack;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public Test() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
        DBConnect DB = new DBConnect();
    }
}

Class to call At Test.java: 在Test.java上调用的类:

package duck.reg.pack;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DBConnect {
    private Connection con;
    private Statement st;

    public DBConnect(){
        System.out.println("Hi there!");
        return;
    }
}

Both File Directory Location: 两个文件目录的位置:

C:\classes\duck\reg\pack\Test.java  +  DBConnect.java

The problem is that when I compile the program with command: 问题是当我使用命令编译程序时:

C:\classes\duck\reg\pack>javac -cp "C:\Users\Unknown\JavaEEWorkspace\lib\*" Test.java

This error is thrown: 引发此错误:

Test.java:16: error: cannot find symbol DBConnect connect = new DBConnect(); Test.java:16:错误:找不到符号DBConnect connect = new DBConnect();

I googled a little and I found I could remove the .java Extension from Test while compiling it and I did so But Then I got this error: 我在Google上搜索了一下,发现可以在编译时从Test中删除.java扩展名,但是这样做了,但是然后出现了这个错误:

error: Class names, 'Test', are only accepted if annotation processing is explicitly requested 1 error 错误:仅在显式请求注释处理的情况下,才接受类名“ Test” 1错误

All replies are much appreciated :) 非常感谢所有答复:)

You need to run the compiler from the top package (which is at the root of the tree on the filesystem). 您需要从顶层软件包(位于文件系统树的根目录)中运行编译器。 So cd to 所以cd到

cd C:\classes

And run 然后跑

javac -cp "C:\Users\Unknown\JavaEEWorkspace\lib\*" duck\reg\pack\*.java

为了找到DBConnect,我们需要使用-cp(或-classpath)选项来指定包com.yyy的基本目录。

javac -cp "d:\lib\*" d:\myJavaProject\pkg\*.java

write at the top 写在顶部

import duck.reg.pack.DBConnect;

in the class that you want to import it. 在您要导入它的类中。

Why don't you use IntelliJ it will do it for you ? 您为什么不使用IntelliJ,它将为您做呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM