Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java checkstyle rule for non-static variable access to static variables

Is there a Checkstyle rule available to restrict non-static access to static variables and methods?

This should raise a warning:

instance.staticField = value;

Eclipse has a setting for this, but I want to enforce it on the build.

like image 307
Jeff Storey Avatar asked Jun 20 '12 14:06

Jeff Storey


2 Answers

I guess using javac -Xlint:static -Werror toto.java is what you're looking for.

From documentation :

  • -Xlint:name : Enable warning name. See the section Warnings That Can Be Enabled or Disabled with -Xlint Option for a list of warnings you can enable with this option.

  • -Werror : Terminate compilation if warnings occur.

I tried with this example :

public class StaticTest {
    public static String toto = "toto";

    public static void main(String s[]) {
        StaticTest st = new StaticTest();
        st.toto="dfd";
    }
}

and the output is:

StaticTest.java:16: warning: [static] static variable should be qualified by type name,

StaticTest, instead of by an expression

   st.toto="dfd";

     ^

error: warnings found and -Werror specified 1 error 1 warning

like image 95
alain.janinm Avatar answered Oct 23 '22 11:10

alain.janinm


As it name indicates it, Checkstyle only check the form of your code. If you search bug patterns, you should take a look at Findbugs:

http://findbugs.sourceforge.net

like image 41
Alexis Dufrenoy Avatar answered Oct 23 '22 09:10

Alexis Dufrenoy