Java Sonar NullPointerException

I have error

A "NullPointerException" could be thrown; "btn" is nullable here.

on code:

Button btn = getButton();
Assert.assertNotNull ("No button", btn);
btn.click();

How I can resolve this problem except case:

Button btn = getButton();
if (btn != null) {
  btn.click();
}

Upvotes: 0

Views: 533

Answers (2)

agabrys
agabrys

Reputation: 9116

I think Assert should be used only in test classes. You can replace it with java.util.Objects#requireNonNull (require Java 7):

Button btn = getButton();
Objects.requireNonNull(bnt).click();

or

Button btn = Objects.requireNonNull(getButton());
bnt.click();

Upvotes: 0

flyingfox
flyingfox

Reputation: 13506

If you are using java-8,then you can use Optional

Optional<Button> btn = getButton();//need to let return to Optional<Button>
btn.ifPresent(b -> b.click());

Upvotes: 1

Related Questions