简体   繁体   中英

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.

I have following directory structure

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

the source code are as follows

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

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

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

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

however its failing stating unable to find class 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:

javac -classpath . source\src\Test2.java

where . is pointing to the current folder which is the folder that contains classes folder.


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.

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". In your case "classes" directory is the root folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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