简体   繁体   中英

javac “cannot find symbol” error with command line

I have two classes Owning and OwningAccessor. The files are in the same directory.

public class Owning {
    String _name = "";
    public void printBanner()
    {
    }
    public void printOwning(double amount)
    {
        printBanner();

        //print details
        System.out.println("name:" + _name);
        System.out.println("amount:" + amount);
    }
}


public class OwningAccessor {
    public void access()
    {
        Owning o = new Owning();
        o.printOwning(500);
    }
}

When I tried to compile OwningAccessor with javac -cp . OwningAccessor.java javac -cp . OwningAccessor.java , I got compilation error.

symbol  : class Owning
location: class smcho.OwningAccessor
        Owning o = new Owning();
        ^
OwningAccessor.java:6: cannot find symbol
symbol  : class Owning
location: class smcho.OwningAccessor
        Owning o = new Owning();
                   ^

What's wrong with this? The code compiles fine under eclipse IDE.

Ok, let's suppose you have the code distributed in files as follows

myproject
├── out
└── src
    ├── OwningAccessor.java
    └── Owning.java

Go to your command prompt, and change directory to myproject . Once there issue the following command:

javac -d out -sourcepath src src/OwningAccessor.java

I just tested it and it works just fine. Your compiled classes will be located in the out folder:

.
├── out
│   ├── OwningAccessor.class
│   └── Owning.class
└── src
    ├── OwningAccessor.java
    └── Owning.java

Compiling one class will trigger the compilation of all other dependent classes. The compiler will automatically look for them in the src folder.

Make sure you compile both Owning.java and OwningAccessor.java, like so:

javac -cp . Owning.java OwningAccessor.java

Eclipse compiles all necessary files for you, which is why does work there.

Try to make a correct sourcepath example:

javac -d temp -sourcepath c:\awork\JavaProjects\singleton\src\ c:\JavaProjects\singleton\src\com\company\MySingleton.java

javac -d temp -sourcepath c:\awork\JavaProjects\singleton\src\ c:\JavaProjects\singleton\src\com\company\Main.java

In "temp" we alocate resources and with -sourcepath indicate where are the .java files.

So, in a directory named D:\\Automation there is a file Demo.java throwing this error, in cmd while you are in D:\\Automation, you need to : - 1) cd.. //will pull you out from Automation directory. In D:> 2) javac Automation\\Demo.java

this will compile your file - Demo.java

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