https://github.com/codebox/checkstyle-import-checker
A Java class to simplify writing custom Checkstyle rules that examine class imports
https://github.com/codebox/checkstyle-import-checker
Last synced: 7 months ago
JSON representation
A Java class to simplify writing custom Checkstyle rules that examine class imports
- Host: GitHub
- URL: https://github.com/codebox/checkstyle-import-checker
- Owner: codebox
- License: mit
- Created: 2014-10-11T06:07:53.000Z (over 11 years ago)
- Default Branch: master
- Last Pushed: 2015-11-14T09:29:47.000Z (about 10 years ago)
- Last Synced: 2023-03-11T21:48:07.895Z (almost 3 years ago)
- Language: Java
- Homepage: http://codebox.org.uk/pages/writing-checkstyle-rules-for-imports
- Size: 129 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# checkstyle-import-checker
[AbstractImportChecker.java](https://github.com/codebox/checkstyle-import-checker) simplifies the process of writing [custom CheckStyle rules](http://checkstyle.sourceforge.net/writingchecks.html) that examine class imports.
Note that Checkstyle contains a number of quite flexible [built-in rules for managing imports](http://checkstyle.sourceforge.net/config_imports.html), you should obviously use these if they meet your needs.
To implement your own custom import checker just sub-class `AbstractImportChecker` and provide an implementation for `onImport()`:
public class ImportChecker extends AbstractImportChecker {
@Override
public void onImport(String packageName, String importName) {
if (! isImportAllowedInPackage(packageName, importName)) {
logError(String.format("Import %s not allowed in package %s", importName, packageName));
}
}
private boolean isImportAllowedInPackage(String packageName, String importName) {
return true; // custom logic here
}
}
The `DottedPath` helper class can be used to check for sub-packages and package membership:
private boolean isImportAllowedInPackage(String packageName, String importName){
DottedPath packagePath = new DottedPath(packageName);
DottedPath importPath = new DottedPath(importName);
return importPath.isChildOf(packagePath);
}