Java does not compile .class files in $ CLASSPATH

I am trying to figure out how to organize source and class files that work with packages. I found a very useful tutorial . But I still have some questions.

As I understand it, isomorphism between package names and the name of the directories in which the package items are stored is a good practice. For example, if I have a package called aaa.bbb.ccc that contains the ddd class, it is good practice to have a class file named "ddd.class" located in "$ CLASSPATH / aaa / bbb / ccc /". Did I understand correctly?

If so, will the Java compiler put the * .class files in the correct directory automatically?

I could not get this behavior. I set the $CLASSPATH variable to "/home/myname/java/classes" . I executed javac KeyEventDemo.java which contains package events; . I expected javac to create an events subdirectory under /home/myname/java/classes and put KeyEventDemo.class in this subdirectory.

That did not happen. I tried to help javac and created the "events" subdirectory myself. I used javac again, but it does not want to put class files under "/ home / myname / java / classes / events". What am I doing wrong?

+4
source share
3 answers

You need to use the -d option to specify where you want the .class files to end. Just specify the base directory; javac will create any directories necessary to match the correct package.

Example (for your question):

 javac -d ~/java/classes KeyEventDemo.java 
+6
source

For example, if I have a package named "aaa.bbb.ccc" that contains the class "ddd", it is good practice to have a file of the class "ddd.class" and located in "$ CLASSPATH / aaa / bbb / ccc /". Did I understand correctly?

This is not β€œgood practice,” Sun JDK thinks. Otherwise it will not work. Theoretically, other Java implementations might work differently, but I don't know what to do.

If so, will the Java compiler put the * .class file in the correct directory automatically?

Yes

What am I doing wrong?

The source code must also follow this structure, i.e. KeyEventDemo.java should be in a subdirectory named "events". Then you do the "javac / KeyEventDemo.java events" and it should work.

+4
source

In most cases, this is not only good practice, but a must .

consider a Java class named:

 com.example.Hello 

If you store it in the file system, it should get to

 /path/to/my/classes/com/example/Hello.java 

The compiler (or at least the vast majority) will create a class file in

 /path/to/my/classes/com/example/Hello.class 

Personally, I would not use the CLASSPATH variable to set the path, but the -cp parameter in java. A call to the above β€œapplication” can be made using:

 java -cp /path/to/my/classes com.example.Hello 
+2
source

Source: https://habr.com/ru/post/1299436/


All Articles