Andrew
Andrew

Reputation: 6880

Is there a way to call checkstyle from within a Java program?

I have a Java program that creates a list of filepaths I want to run checkstyle on. I was curious if there is a way to directly run checkstyle from within my program or whether I will need to shell out to the CLI.

Upvotes: 6

Views: 704

Answers (3)

Ellen Spertus
Ellen Spertus

Reputation: 6815

See Invoking Checkstyle directly from Java, which points a user to the class com.puppycrawl.tools.checkstyle.api, which is the suggested way to interface with checkstyle programmatically.

Upvotes: -1

barfuin
barfuin

Reputation: 17494

Yes, that is possible, although it's not so much a documented API, but rather a set of calls that works, and that's kept reasonably stable. In fact, IDE plugins go that way.

For example, the Checkstyle plugin for IntelliJ has some code you can look at to get an idea:
https://github.com/jshiell/checkstyle-idea/tree/5.26.0/src/csaccess/java/org/infernus/idea/checkstyle/service/cmd

It may, however, be easier to just call Checkstyle as a command-line program (via zt-exec, for example) and parse its XML report. That is if you don't need to have the direct feedback provided via in-process AuditListeners.

Upvotes: 6

rveach
rveach

Reputation: 2201

I have a Java program
is a way to directly run checkstyle from within my program

You can call any Java program from within another Java program. When a Java program is called from the command line, it's main method is called that passes in all the command line parameters that is not for the java program itself. All you need to do in your Java program is call the same main that the command line calls. For checkstyle this is com.puppycrawl.tools.checkstyle.Main. See https://github.com/checkstyle/checkstyle/blob/bd7621fae3b1b887d46b8a678600db7e6d03185c/src/main/java/com/puppycrawl/tools/checkstyle/Main.java#L100 .

The downside to checkstyle however is it calls System.exit when it is done so you will never return from your call. To prevent a System.exit from terminating the JVM completely see Java: How to test methods that call System.exit()? for the SecurityManager example.

You can avoid all this System.exit business but it would require you to duplicate a bunch of Checkstyle's code, which is also in the Main class. See https://github.com/checkstyle/checkstyle/blob/bd7621fae3b1b887d46b8a678600db7e6d03185c/src/main/java/com/puppycrawl/tools/checkstyle/Main.java#L332 . It is up to you how you want to handle it.

Upvotes: 1

Related Questions