简体   繁体   中英

Where do you store Java .class files, conventionally?

I have a Java src folder in which I store my .java files. I then compile them using Terminal and end up getting .class files in the same directory. This doesn't necessarily bother me, but I've never seen that being done professionally.

By professional convention (if there exists one), in what folder in a project's directory should you store compiled .class files?

If you're not familiar with it, you should look into the subject of the Java classpath . I can remember finding this confusing when I first started programming in Java.

There is a defined search path for .class files in Java; when you run java -cp blahblahblah that sets the classpath. java -jar blahblahblah.jar opens a JAR file and the .jar file's manifest may dictate the classpath. The default classpath is in the current directory.

Usually you put Java classes in packages in a hierarchical directory structure in the filesystem, in which case the Java compiler will also put .class files in a corresponding structure.

If you run javac from the command line, the -d argument specifies the destination root directory for .class files.

A typical project looks like this, assuming your package is called com.example.foo and it contains Foo.java and Bar.java:

project_dir/
   src/
      com/
         example/
            foo/
               Foo.java
               Bar.java
   bin/
      com/
         example
            foo/
               Foo.class
               Bar.class

The java compiler will be executed with -d bin as a destination directory, and it will create the .class files corresponding to the .java files. But the destination doesn't have to be called bin ; you could call it Freddy or dumbass if you wanted to, although that would probably confuse people used to bin or build .

Most of the time when a Java program or library builds, the .class files are just a temporary step towards building a .jar file (essentially just a .zip format with a .jar extension, containing the .class files and a little bit of metadata), and when you actually run them, Java will use the .jar file if you include it as part of the classpath.

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