简体   繁体   中英

How do I compile a Java class which uses another Java class as an Object?

I have an A.java class which uses B.java class as an object.

When I compile A.java class, it throws a compile error message, since the Java compiler can not reference the B.java object at all. So, here is my question:

How do I compile A.java class if it includes another B.java class?

Eclipse is a great tool, but this tool is not useful when I need to compile a Java file for Java beans.

You haven't explained how you're trying to compile A.java, or whether you've already compiled B.java. If you haven't compiled either of them yet, just compile them both together, eg

javac -d bin path/to/A.java path/to/B.java

If you've already compiled B, you need to make sure you've got the classpath right, eg

javac -d bin -cp path/to/Broot path/to/A.java

Note that the classpath value shouldn't be the B.class file itself, nor even the directory containing B.class - but the root of the output hierarchy. So if B is in package foo.bar, and B.class is in directory /x/y/z/foo/bar you'd write:

javac -d bin -cp /x/y/z path/to/A.java

The error seems to be that the class B is not yet compiled. Could you check class B for errors, compile B, and then go for A?

编译类时,请确保依赖项(jar文件)和当前目录在类路径中。

This is a duplicate of the question: Can I use JAVAC to compile a project with multiple files and directories?

Depending on the type of object B you must add it to the classpath. If it's in a jar file (library) you should the -c option on command line. For adding other source files use the -s option.

Once you start bigger projects it will be hard to keep doing this manually on the command line. Look at a proper IDE like eclipse. It does all that for you. You only have to set the classpath in the properties once and then you can just compile with the click of some menu options (or set automatic building or use shortcut keys).

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