Skip to content

Generic type variable doesn't respect @NonNull annotation on the generic tpye. #7104

@baeminbo

Description

@baeminbo

The generic type Bar<T> is defined with a non-null constraint (@NonNull T). Therefore, the type variable T inherits this @NonNull annotation. As a result, the value variable in the example should be treated as non-null.

  public interface Foo<@NonNull T> {
    T foo(T input);
  }

  public static class Bar<@NonNull T> {
    T value;

    public Bar(Foo<T> foo, T input) {
      this.value = foo.foo(input);
    }

    public String bar() {
      return value.toString();
    }
  }

However, the compilation failed with "error: [dereference.of.nullable] dereference of possibly-null reference value" at the line of value.toString() . Could you please clarify why this occurs?

Interestingly, if the generic constraint is changed from @NonNull T to T extends @NonNull Object for Bar, the compilation succeeds. While the manual suggest that @NonNull T and T extends @NonNull Object are the same, this result show they behave differently. Could you please explain this as well?

The version 3.49.4 was used for the test.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions