Search code examples
javaannotationscheckstyle

Checkstyle - Method with annotation must be before constructor


How can I define a Checkstyle validation to make sure that all the methods with a specific annotation appear before the constructor of a java class?

The following should be accepted by the validation:

class User {

    @Injected // -> [OK]: method with @Injected is before the constructor. 
    public void setName(String name) {
        this.name = name;
    }

    public User(String name) {
        this.name = name;
    }
}

The following should be causing a Checkstyle violation:

class User {
    public User(String name) {
        this.name = name;
    }

    @Injected // -> [NOK]: method should be before the constructor
    public void setName(String name) {
        this.name = name;
    }
}

Is there a Checkstyle Check available out of the box that could be configured to check this or a custom Check implemenation is needed to implement this?


Solution

  • No, there is no such Checkstyle Check available out of the box.

    One needs to implement a custom Checkstyle Check for this purpose and this custom validation must be triggered by adding it in the validation configuration xml.