Dear All,
I need a null check rule for an object, before we retrieve values from an object.
eg: Class Foo{
int A; String B; . . }
if (foo.getA() > 5){ }
If any operation is done on the object without a null check, it has to be highlighted and logged.. Thanks in anticipation!
I would recommend to check out the rules MisplacedNullCheck and BrokenNullCheck.
Example with XPath (beware - it might have lots of false positives/negatives):
<rule name="NullCheck" message="Null Check is required." class="net.sourceforge.pmd.lang.rule.XPathRule" language="java"> <description> </description> <properties> <property name="xpath"> <value> <![CDATA[ //IfStatement/Expression [.//PrimarySuffix[../PrimaryPrefix/Name[contains(@Image, '.')]]] [ count(.//NullLiteral[ancestor::EqualityExpression[@Image='!='] [starts-with(following-sibling::*/PrimaryExpression/PrimaryPrefix/Name/@Image,./PrimaryExpression/PrimaryPrefix/Name/@Image)] ]) = 0] ]]> </value> </property> </properties> <priority>3</priority> <example> <![CDATA[ public class Foo{ int A; public int getA() { return A; } public static void check() { Foo foo = new Foo(); Foo bar = new Foo(); // missing null check if (foo.getA() > 5){ } // missing null check if (bar != null && foo.getA() > 5) {} // correct null check if (foo != null && foo.getA() > 5) { } } } ]]> </example> </rule>
Thanks a ton!! :) I will take it further by testing rigorously, and keep you posted..
Thank you very much again.
Hi Andreas,
it is not working when I try to add it as a rule in eclipse-pmd plugin.
Please give me some pointers to look into..
Thanks.
Log in to post a comment.
Dear All,
I need a null check rule for an object, before we retrieve values from an object.
eg:
Class Foo{
int A;
String B;
.
.
}
if (foo.getA() > 5){
}
If any operation is done on the object without a null check, it has to be highlighted and logged..
Thanks in anticipation!
I would recommend to check out the rules MisplacedNullCheck and BrokenNullCheck.
Example with XPath (beware - it might have lots of false positives/negatives):
Last edit: Andreas Dangel 2014-11-15
Thanks a ton!! :)
I will take it further by testing rigorously, and keep you posted..
Thank you very much again.
Hi Andreas,
it is not working when I try to add it as a rule in eclipse-pmd plugin.
Please give me some pointers to look into..
Thanks.
Last edit: 512Renee 2014-11-25