简体   繁体   English

无法理解Java中的类路径

[英]Unable to understand the classpath in java

I am having hard time understanding the concept of classpath even though after going through oracle document.Please help me out in this. 即使经过oracle文档,我也很难理解classpath的概念。请帮助我。

I have following directory structure 我有以下目录结构

Sample
|
-----source
|       |
|       src
|        |
|       Test2.java
|
------classes
        |
       com
        |
       Test1.java

the source code are as follows 源代码如下

Test1.java Test1.java

package classes.com;

public class Test1
{
    public static void main(String[] args)
    {
        System.out.println("In file Test1 in com package....");
    }
}

Test2.java Test2.java

package source.src;

public class Test2
{
    public static void main(String[] args)
    {
        Test1 test=new Test1();
        System.out.println("In class src..Test2...");
    }
}

I compiled Test1.java as 我将Test1.java编译为

Q:\Sample>javac classes\com\Test1.java

and it works fine 而且效果很好

Now since Test2.java has dependency on Test1.java so i am suing the below command 现在,由于Test2.java依赖于Test1.java,所以我在使用以下命令

javac -classpath classes\com source\src\Test2.java

however its failing stating unable to find class Test1. 但是,它未能说明无法找到类Test1。

Not sure what i am doing wrong.Need Help 不知道我在做什么错。需要帮助

Regardless of the wrong structure, you need to set the classpath to the top level folder where it contains the full package name ( classes/com/Test1.java ), ie: 无论结构如何,都需要将类路径设置为包含完整包名称( classes/com/Test1.java )的顶级文件夹,即:

javac -classpath . source\src\Test2.java

where . 在哪里. is pointing to the current folder which is the folder that contains classes folder. 指向当前文件夹,该文件夹是包含classes文件夹的文件夹。


Also, you forgot to include the import statement: 另外,您忘记了包含导入语句:

import classes.com.Test1;

First of all your source files are not organized properly. 首先,您的源文件未正确组织。 Keep all your .java files under your source directory and have the "classes" or "build" directory to store the .class files. 将所有.java文件保留在源目录下,并具有“ classes”或“ build”目录来存储.class文件。

When running your applications make sure the "classes" or "build" directory is added as a classpath. 运行应用程序时,请确保将“类”或“构建”目录添加为类路径。

The root directory where your classes are stored should be set as "classpath". 存储您的类的根目录应设置为“ classpath”。 In your case "classes" directory is the root folder. 在您的情况下,“ classes”目录是根文件夹。

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

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