0

Hi i have the following code.

if (SecurityContextHolder.getContext().getAuthentication() != null
                && SecurityContextHolder.getContext().getAuthentication()
                        .getPrincipal() instanceof User)

When I check with pmd it is giving me an warning: No need to check null before instanceof.

Q1.) How do you fix this warning? -- if i just do security SecurityContextHolder.getContext().getAuthentication().getPrincipal() and getAuthentication is null than I would get NPE (Null pointer exception).

Chun ping Wang
  • 3,879
  • 12
  • 42
  • 53
  • You might want to look at http://stackoverflow.com/questions/2950319/is-null-check-needed-before-calling-instanceof: if the value is null, `instanceof` returns `false`. – tonio May 02 '12 at 13:38
  • Tonio, you might want to re-read the question. He can't safely get the value without checking an intermediate result for null. – Chris Morley May 07 '12 at 18:41

2 Answers2

2

I think this is a bug in PMD because I face the same problem. Maybe the XPath Expression for this pattern is not clear enough. But it is already fixed. See http://sourceforge.net/tracker/index.php?func=detail&aid=2317099&group_id=56262&atid=479921

ambassador86
  • 161
  • 1
  • 5
1

If you can't use the fixed version of PMD, add a temporary variable

... principal = null;
if (SecurityContextHolder.getContext().getAuthentication() != null)
   principal = SecurityContextHolder.getContext().getAuthentication()
                    .getPrincipal();
if (principal instanceof User) ...
Chris Morley
  • 891
  • 6
  • 16