Reputation: 46492
Non-public top-level (i.e., package-private) classes in Java do not require the file name to match (e.g., class Foo may be defined in Bar.java). I don't think such a feature is of any use any more (since nested classes were introduced many years ago).
Sometimes it leads to problems: After some refactorings I ended with file names not matching their class names, which confused me (while committing) and also Eclipse (some files weren't recompiled although they had to).
Is there a way how to forbid such classes in Eclipse?
Upvotes: 2
Views: 728
Reputation: 28707
I'd recommend using Checkstyle, which also has a very nice plugin for Eclipse, eclipse-cs. In the eclipse-cs configuration for a given check configuration, under Miscellaneous, there is a check for "Outer Type File Name" that can be enabled, with a description of "Checks that the outer type name and the file name match. For example, the class Foo must be in a file named Foo.java.".
In order to truly "forbid such classes", this check can even be set to have an "error" severity (which by default, will prevent a build, at least in Eclipse) - instead of the default "warning" severity.
As an added bonus, using Checkstyle doesn't lock you in to running this check within Eclipse. Checkstyle is easily integrated into various build tools such as Apache Maven, allowing this issue to be checked for even if you or another user weren't using Eclipse.
Upvotes: 1