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

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-11 04:53:06

问题


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?


回答1:


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 :)



来源:https://stackoverflow.com/questions/8310518/dont-packages-have-to-match-the-subdirectories-the-java-file-is-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!