Java class name same as the nested package name

后端 未结 5 833
悲哀的现实
悲哀的现实 2020-12-19 15:40

In my Java application, I use a third-party library.

However, I found something strange, there are some nested packages, and some classes whose name may be the same

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 16:11

    The Java language allows class identifiers to be obscured by package identifiers. In your case the class com.xx.a is obscured by the package com.xx.a.

    From the Java Language Specification:

    6.3.2 Obscured Declarations

    A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package. Thus, it may sometimes be impossible to refer to a visible type or package declaration via its simple name. We say that such a declaration is obscured.

    I must say that the rules in §6.5 for classifying the meaning of an identifier are far from clear though.

    The reason why you still happen to have a copy of a library that violates this rule is because the rule does not apply for class files / JAR files and the JVM.

    This means that you can have such naming conflicts in JAR files, but you'll never see it as output from javac. The tool that has produced these class / package names is most likely a code obfuscator which produces this kind of messy code to compress the size of the files and to obfuscate the code to prevent reverse engineering.


    PS. At a closer look it may actually be a bug on the Eclipse side (assuming that's the IDE you're talking about). By letting an empty package name collide with a class name, Eclipse chokes on something javac accepts. The spec is hard to follow, but from what I can see, javac follows the spec in this case.

提交回复
热议问题