CheckForNull annotation in Adaptable.adaptTo | Community
Skip to main content
Level 4
October 18, 2016
Solved

CheckForNull annotation in Adaptable.adaptTo

  • October 18, 2016
  • 3 replies
  • 2640 views

Hello,

I would like to discuss Adaptable.adaptTo().

This method has annotation CheckForNull.

For example I have some part of code:

Session session = resourceResolver.adaptTo(Session.class); Node node = session.getNode("somepath");

Sonar will have blocker issue - NullPointerException might be thrown as 'session' is nullable here

From one side resourceResolver should always return non null Session (If it return null, that means that something wrong with AEM instance).

From the other side checkfornull force to add additional check that session != null.

Should we add check for null in current situation or not?

Thanks

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by Pawan-Gupta

I would say, it doesn't require to check for null because if you look at the details about adaptTo() it says "The adapter target or null if the resource cannot adapt to the requested type" it means will only return null if resourceResolver object (if exist) can not map to session (type) and it will be initialized from request anyhow similar as (request.getSession(true/false))

3 replies

smacdonald2008
Level 10
October 18, 2016

Checking for a null is not a bad practice and ensures that the object has memory allocated to it. 

Anton_Smulskiy
Level 3
October 18, 2016

Hi Alex,

Maybe it's a bad practice, but I check for null only if there is a real chance to get null returned.

in this case I don't check:

Session session = resourceResolver.adaptTo(Session.class);

But when I'm not sure if resource can be adapted to my model, I check for null:

MyModel myModel = resource.adaptTo(MyModel.class); if (myModel == null) { // do something }
Pawan-Gupta
Pawan-GuptaAccepted solution
Level 8
October 18, 2016

I would say, it doesn't require to check for null because if you look at the details about adaptTo() it says "The adapter target or null if the resource cannot adapt to the requested type" it means will only return null if resourceResolver object (if exist) can not map to session (type) and it will be initialized from request anyhow similar as (request.getSession(true/false))