How can I avid a NullPointerException warning in this lambda Java expression code?

How can I prevent a NullPointerException warning in this Java code? I am working with IntelliJ and I get this warning:

Calling the "getChartController ()" method may throw 'java.Lang.NullPointerException' "

chartControlButtons.add(
    new JButton("Zoom In") {{
        addActionListener(
            (ActionEvent e) -> getChartController().zoomIn()
        );
    }}
);

thank

+4
source share
1 answer

You can use the option to avoid NullPointerExceptions.

The following is an example of using this case.

     chartControlButtons.add(
        new JButton("Zoom In") {{
          addActionListener(
              (ActionEvent e) -> Optional.ofNullable(getChartController()).ifPresent(s -> s.zoomIn())
          );
        }}
    );
+1
source

Source: https://habr.com/ru/post/1696345/


All Articles