Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java not compiling .class files under $CLASSPATH

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

As far as I understood it is a good practice to have an isomorphism between name of packages and name of the directories where elements of a package are stored. For example if I have a package named aaa.bbb.ccc which contains class ddd it is a good practice to have a class file called "ddd.class" and located in "$CLASSPATH/aaa/bbb/ccc/". Did I get it right?

If it is the case, will Java compiler put *.class files into the correct directory automatically?

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

It did not happen. I tried to help to javac and created "events" subdirectory by 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?

like image 589
Roman Avatar asked Dec 17 '22 03:12

Roman


2 Answers

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

Example (based on your question):

javac -d ~/java/classes KeyEventDemo.java
like image 84
Chris Jester-Young Avatar answered Dec 19 '22 16:12

Chris Jester-Young


For example if I have a package named "aaa.bbb.ccc" which contains class "ddd" it is a good practice to have a class file called "ddd.class" and located in "$CLASSPATH/aaa/bbb/ccc/". Did I get it right?

That's not "good practice" - this is how the Sun JDK expects things to be. Otherwise, it will not work. Theoretically, other Java implementations could work differently, but I don't know any that do.

If it is the case, will Java compiler put *.class file into a correct directory automatically?

Yes

What am I doing wrong?

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

like image 24
Michael Borgwardt Avatar answered Dec 19 '22 17:12

Michael Borgwardt