包不是必须匹配java文件所在的子目录吗? [英] Don't packages have to match the subdirectories the java file is in?

查看:207
本文介绍了包不是必须匹配java文件所在的子目录吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天早上正在为我的java认证编写一些练习程序,并注意到我输入了一个包名,所以它与java文件所在的子目录不匹配。我编译代码期待错误,但是一切编译文件 - 甚至不是警告。

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.

当我试图运行程序时,它不起作用,因为.class文件位于错误的目录中。我将它移动到正确的目录,并收到此错误:

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)

所以我认为我看到的是,如果软件包和子目录不匹配,Java代码将编译,但是没有似乎是一种运行代码的方法,如果你这样做。这是正确的吗?

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?

推荐答案

包名称必须与目录名称匹配,以便文件找到正确。对于某些编译器(例如javac),它不会拥有来匹配编译时的目录名称,尽管其他编译器(例如Eclipse)至少会发出警告。

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.

请注意,如果使用 -d 标志,javac将为您构建适当的目录层次结构,而不管源位置如何。例如:

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

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

这篇关于包不是必须匹配java文件所在的子目录吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆