且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java类名称的区分大小写

更新时间:2023-02-15 17:37:39



  • 是否可以保证每个JVM中的引导类加载器可以加载哪些类?

语言的核心部分,以及支持实现类。不保证包括您编写的任何课程。 (普通的JVM在一个单独的类加载器中将类加载到引导程序中,实际上正常的引导程序加载程序通常会从JAR中加载它的类,因为这比一个充满类的大型旧目录结构更有效。)

The core bits and pieces of the language, plus supporting implementation classes. Not guaranteed to include any class that you write. (The normal JVM loads your classes in a separate classloader from the bootstrap one, and in fact the normal bootstrap loader loads its classes out of a JAR normally, as this makes for more efficient deployment than a big old directory structure full of classes.)



  • 如果有任何保证,上述示例中的行为是否违反了保证(即行为)一个错误)?

  • 有没有办法让标准JVM同时加载a和A?编写自定义类加载器是否有效?

Java通过映射类的全名加载类到文件名,然后在类路径上搜索。因此 testcase.a 转到 testcase / a.class testcase.A 转到 testcase / A.class 。有些文件系统将这些东西混合在一起,并且可以在需要时为另一个提供服务。其他人做得对(特别是,JAR文件中使用的ZIP格式的变体完全区分大小写并且是可移植的)。 Java无法做到这一点(尽管IDE可以通过保持 .class 文件远离本机FS来处理它,我不知道是否有任何文件实际上和JDK的 javac 肯定不是那么聪明。

Java loads classes by mapping the full name of the class into a filename that is then searched for on the classpath. Thus testcase.a goes to testcase/a.class and testcase.A goes to testcase/A.class. Some filesystems mix these things up, and may serve the other up when one is asked for. Others get it right (in particular, the variant of the ZIP format used in JAR files is fully case-sensitive and portable). There is nothing that Java can do about this (though an IDE could handle it for you by keeping the .class files away from the native FS, I don't know if any actually do and the JDK's javac most certainly isn't that smart).

然而,这不是唯一的指向请注意:类文件在内部知道他们在谈论什么类。文件中缺少期望的类只意味着加载失败,导致您收到的 NoClassDefFoundError 。你得到的是一个问题(至少在某种意义上的错误部署),这个问题被强有力地检测和处理。从理论上讲,你可以构建一个可以通过保持搜索来处理这类事情的类加载器,但为什么要这么麻烦?将类文件放在JAR中可以更加强大地解决问题。这些都是正确处理的。

However that's not the only point to note here: class files know internally what class they are talking about. The absence of the expected class from the file just means that the load fails, leading to the NoClassDefFoundError you received. What you got was a problem (a mis-deployment in at least some sense) that was detected and dealt with robustly. Theoretically, you could build a classloader that could handle such things by keeping searching, but why bother? Putting the class files inside a JAR will fix things far more robustly; those are handled correctly.

更一般地说,如果你真的遇到这个问题很多,那么在带有区分大小写的文件系统的Unix上进行生产构建(建议像Jenkins这样的CI系统)并且找出哪些开发人员只是在案例差异的情况下命名类,并且让它们停止,因为它非常混乱!

More generally, if you're running into this problem for real a lot, take to doing production builds on a Unix with a case-sensitive filesystem (a CI system like Jenkins is recommended) and find which developers are naming classes with just case differences and make them stop as it is very confusing!