Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't packages have to match the subdirectories the java file is in?

Tags:

java

package

I was writing some practice programs for my java certification this morning, and noticed that I had mistyped a package name, so it didn't match the subdirectory the java file was in. I compiled the code expecting an error, but everything compiled file -- not even a warning.

I googled around a bit, and most of the pages I read said that the package name had to match the subdirectory. My experience shows that's not the case.

When I attempted to run the program, it didn't work because the .class file was in the wrong directory. I moved it to the correct directory, and got this error:

Exception in thread "main" java.lang.NoClassDefFoundError: com/sample/directory
/doesnt/even/exist/OtherPackageMemberModifiers (wrong name: com/sample/chap01/O
therPackageMemberModifiers)

So what I think I'm seeing is that Java code will compile if the package and the subdirectory don't match up, but there doesn't seem to be a way to run the code if you do that. Is that correct?

like image 626
jonny five Avatar asked Nov 29 '11 12:11

jonny five


1 Answers

The package name has to match the directory name in order for the class file to be found correctly. It doesn't have to match the directory name at compilation time for some compilers (e.g. javac) although others (such as Eclipse) will at least give a warning.

The "way to run the code if you do that" is to create the directory structure and put it in there manually - the class file itself is entirely valid.

Note that if you use the -d flag, javac will build the appropriate directory hierarchy for you, regardless of source location. For example:

javac -d bin ClassInPackage.java

will create any required directories under bin to match the package declared in ClassInPackage.java.

Having said all of thise, I'd still strongly encourage you to make the source directories match the packages, even though you can get away without it :)

like image 184
Jon Skeet Avatar answered Sep 19 '22 12:09

Jon Skeet