PackageDeclaration

Since Checkstyle 3.2

Description

Ensures that a class has a package declaration, and (optionally) whether the package name matches the directory name for the source file.

Rationale: Classes that live in the null package cannot be imported. Many novice developers are not aware of this.

Packages provide logical namespace to classes and should be stored in the form of directory levels to provide physical grouping to your classes. These directories are added to the classpath so that your classes are visible to JVM when it runs the code.

Properties

name description type default value since
matchDirectoryStructure Control whether to check for directory and package name match. boolean true 7.6.1

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="PackageDeclaration"/>
  </module>
</module>
        

Example1:

public class Example1{ // violation, 'Missing package declaration'
  String str = "Some Content";
}
        

Example of how the check works when matchDirectoryStructure option is set to false.

<module name="Checker">
  <module name="TreeWalker">
    <module name="PackageDeclaration">
    <property name="matchDirectoryStructure" value="false"/>
    </module>
  </module>
</module>
        

Example2:

package com.nonexistent.packages;
public class Example2{
  String str = "Some Content";
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker