Bug 485739 - Calling method from constructor can trick null annotations
Summary: Calling method from constructor can trick null annotations
Status: NEW
Alias: None
Product: JDT
Classification: Eclipse Project
Component: Core (show other bugs)
Version: 4.5.1   Edit
Hardware: PC Windows 7
: P3 enhancement (vote)
Target Milestone: ---   Edit
Assignee: JDT-Core-Inbox CLA
QA Contact:
URL:
Whiteboard:
Keywords:
Depends on:
Blocks:
 
Reported: 2016-01-13 06:38 EST by Torge Kummerow CLA
Modified: 2016-01-16 05:38 EST (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Torge Kummerow CLA 2016-01-13 06:38:22 EST
Hi,

While adopting my project to Null Annotations, I came across two different special cases where they did not work as I would have expected.
Both are related methods being called from the constructor.

Scenario 1: NPE even though @NonNull is defined and no warnings are present.

class A {
  @NonNull String field;
  
  public A() {
    this.field = update();
  }

  private @NonNull String update() {
    if (this.field.length() < 3)
      return "Test1";

    return "Test2;
  }
}


Scenario 2: Not initialized warning is shown even though the field is initialized jsut fine.

class B {
  @NonNull String field;
  
  public B() {
    init();
  }
  
  private void init() {
    this.field = "Test";
  }
}

I am not sure if this can be fixed easily, maybe taint methods that are called from constructors recursively and threat them accordingly. But if not, maybe enhance the documentation to mention these special cases as limitations.
Comment 1 Stephan Herrmann CLA 2016-01-13 13:01:08 EST
Thanks.

A good test for the logic of our analysis for field initialization is always: try to make the field final and see what the compiler has to say.

Analysis of @NonNull fields is as good but no better than analysis of definite assignment of final fields (before read).

I'd argue that developers should be aware of the dangers of calling methods from a constructor. But, yes, a hint in the documentation is a good idea.
Comment 2 Torge Kummerow CLA 2016-01-16 05:38:45 EST
I thaugt a bit about it and wounder if it would maybe make sense to raise 2 new kinds of warnings when a @NonNull field is assigned in a constructor by either a method call to a method of the same object or by passing "this" as a parameter to another object's method.

Something along the lines: Potential null poiter access to field 'xxx' by calling method of not fully initialized object.

And: Potential null pointer access to field 'xxx' by passing not fully initialized object as parameter.

Of course, only if there actually is a not initialized NonNull field at that point.