0

I have another StackOverflow question on how to install and run a custom checkstyle. I've learned how to do this, and I will update that answer shortly with detailed instructions. Now I am having trouble customizing my check. Below is my code. The problem is I would like to see the fully qualified package as a string (e.g com.amir.foo) - but instead when I run getText() or just toString(), I get some obscure result ([checkstyle] package set to : ANNOTATIONS). Does anyone know how to work with this to achieve the desired results?

import com.puppycrawl.tools.checkstyle.api.*;

public class MyCheck extends Check
{

    FullIdent packageDeclaration;

    public int[] getDefaultTokens() {
        return new int[]{TokenTypes.PACKAGE_DEF};
    }

    public void visitToken(DetailAST ast)
    {

        switch(ast.getType()) {
            case TokenTypes.PACKAGE_DEF:
                System.out.println("got package!");
                visitPackage(ast);
                break;
            default:
                System.out.println("naughty!");
        }

    }

    private void visitPackage(DetailAST pack) {
        packageDeclaration = FullIdent.createFullIdentBelow(pack);
        System.out.println("package set to : " +packageDeclaration);
    }
}

1 Answer 1

2

What your looking for is used by the check for package names, you should use a code similar to the following:

@Override
public void visitToken(DetailAST aAST)
{
    final DetailAST nameAST = aAST.getLastChild().getPreviousSibling();
    final FullIdent full = FullIdent.createFullIdent(nameAST);
    final String package = full.getText();


    // do some fancy stuff with package name
}

For more details please refer to the source code of PackageNameCheck: http://checkstyle.hg.sourceforge.net/hgweb/checkstyle/checkstyle/file/cd352660c53a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/PackageNameCheck.java

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the quick response. Can you explain what this code is doing? Why do we getLastChild then getPreviousSibling?
As a side note, this code will not compile because you're using the package keyword in the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.