Java annotation not null

Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Читайте также:  Python list file types

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

Bean Validation is a standard validation specification that allows us to easily validate domain objects by using a set of constraints declared in the form of annotations.

While overall the use of bean validation implementations, such as Hibernate Validator, are fairly straightforward, it’s worth exploring some subtle, yet relevant, differences regarding how some of these constraints are implemented.

In this tutorial, we’ll explore the differences between the @NotNull, @NotEmpty, and @NotBlank constraints.

Further reading:

Java Bean Validation Basics

Learn the basics of Java Bean validation, the common annotations and how to trigger the validation process.

Validating Container Elements with Jakarta Bean Validation 3.0

Guide to ParameterMessageInterpolator

2. The Maven Dependencies

To quickly set up a working environment and test the behavior of the @NotNull, @NotEmpty, and @NotBlank constraints, first we need to add the required Maven dependencies.

In this case, we’ll use Hibernate Validator, the bean validation reference implementation, for validating our domain objects.

Here’s the relevant section of our pom.xml file:

  org.springframework.boot spring-boot-starter-validation 3.0.4  

This dependency will import the related Hibernate Validator dependency transitively. If not using Spring-Boot, we can just import Hibernate Validator library:

 org.hibernate.validator hibernate-validator 8.0.0.Final 

We’ll use JUnit and AssertJ in our unit tests, so make sure to check the latest versions of hibernate-validator, GlassFish’s EL implementation, junit, and assertj-core on Maven Central.

3. The @NotNull Constraint

Moving forward, let’s implement a naive UserNotNull domain class and constrain its name field with the @NotNull annotation:

Now we need to examine how @NotNull actually works under the hood.

To do so, let’s create a simple unit test for the class, and validate a few instances of it:

@BeforeClass public static void setupValidatorInstance() < validator = Validation.buildDefaultValidatorFactory().getValidator(); >@Test public void whenNotNullName_thenNoConstraintViolations() < UserNotNull user = new UserNotNull("John"); Set> violations = validator.validate(user); assertThat(violations.size()).isEqualTo(0); > @Test public void whenNullName_thenOneConstraintViolation() < UserNotNull user = new UserNotNull(null); Set> violations = validator.validate(user); assertThat(violations.size()).isEqualTo(1); > @Test public void whenEmptyName_thenNoConstraintViolations() < UserNotNull user = new UserNotNull(""); Set> violations = validator.validate(user); assertThat(violations.size()).isEqualTo(0); > 

As expected, the @NotNull constraint won’t allow null values for the constrained field(s). However, the field(s) can be empty.

To better understand this, let’s look at the NotNullValidator class‘ isValid() method, which the @NotNull constraint uses. The method implementation is really trivial:

public boolean isValid(Object object)

As shown above, a field (e.g. CharSequence, Collection, Map, or Array) constrained with @NotNull must be not null. An empty value, however, is perfectly legal.

Читайте также:  What tools to html

4. The @NotEmpty Constraint

Now let’s implement a sample UserNotEmpty class and use the @NotEmpty constraint:

public class UserNotEmpty < @NotEmpty(message = "Name may not be empty") private String name; // standard constructors / getters / toString >

With the class in place, let’s test it by assigning different values to the name field:

@Test public void whenNotEmptyName_thenNoConstraintViolations() < UserNotEmpty user = new UserNotEmpty("John"); Set> violations = validator.validate(user); assertThat(violations.size()).isEqualTo(0); > @Test public void whenEmptyName_thenOneConstraintViolation() < UserNotEmpty user = new UserNotEmpty(""); Set> violations = validator.validate(user); assertThat(violations.size()).isEqualTo(1); > @Test public void whenNullName_thenOneConstraintViolation() < UserNotEmpty user = new UserNotEmpty(null); Set> violations = validator.validate(user); assertThat(violations.size()).isEqualTo(1); >

The @NotEmpty annotation makes use of the @NotNull class’ isValid() implementation, and also checks that the size/length of the supplied object (of course, this varies according to the type of object being validated) is greater than zero.

In a nutshell, this means that a field (e.g. CharSequence, Collection, Map, or Array) constrained with @NotEmpty must be not null, and its size/length must be greater than zero.

Additionally, we can be even more restrictive if we use the @NotEmpty annotation in conjunction with @Size.

In doing so, we’d also enforce that the object’s min and max size values are within the specified min/max range:

@NotEmpty(message = "Name may not be empty") @Size(min = 2, max = 32, message = "Name must be between 2 and 32 characters long") private String name; 

5. The @NotBlank Constraint

Similarly, we can constrain a class field with the @NotBlank annotation:

public class UserNotBlank < @NotBlank(message = "Name may not be blank") private String name; // standard constructors / getters / toString >

Along the same lines, we can implement a unit test to understand how the @NotBlank constraint works:

@Test public void whenNotBlankName_thenNoConstraintViolations() < UserNotBlank user = new UserNotBlank("John"); Set> violations = validator.validate(user); assertThat(violations.size()).isEqualTo(0); > @Test public void whenBlankName_thenOneConstraintViolation() < UserNotBlank user = new UserNotBlank(" "); Set> violations = validator.validate(user); assertThat(violations.size()).isEqualTo(1); > @Test public void whenEmptyName_thenOneConstraintViolation() < UserNotBlank user = new UserNotBlank(""); Set> violations = validator.validate(user); assertThat(violations.size()).isEqualTo(1); > @Test public void whenNullName_thenOneConstraintViolation() < UserNotBlank user = new UserNotBlank(null); Set> violations = validator.validate(user); assertThat(violations.size()).isEqualTo(1); > 

The @NotBlank annotation uses the NotBlankValidator class, which checks that a character sequence’s trimmed length is not empty:

public boolean isValid( CharSequence charSequence, ConstraintValidatorContext constraintValidatorContext) if (charSequence == null ) < return false; >return charSequence.toString().trim().length() > 0; > 

The method returns false for null values.

To put it simply, a String field constrained with @NotBlank must be not null, and the trimmed length must be greater than zero.

6. A Side-by-Side Comparison

So far, we’ve taken an in-depth look at how the @NotNull, @NotEmpty, and @NotBlank constraints operate individually on class fields.

Let’s perform a quick side-by-side comparison, so we can have a bird’s eye view of the constraints’ functionality and easily spot their differences:

  • @NotNull: a constrained CharSequence, Collection, Map, or Array is valid as long as it’s not null, but it can be empty.
  • @NotEmpty: a constrained CharSequence, Collection, Map, or Array is valid as long as it’s not null, and its size/length is greater than zero.
  • @NotBlank: a constrained String is valid as long as it’s not null, and the trimmed length is greater than zero.
Читайте также:  Count all characters python

7. Conclusion

In this article, we looked at the @NotNull, @NotEmpty, and @NotBlank constraints implemented in Bean Validation, and highlighted their similarities and differences.

As usual, all the code samples shown in this article are available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Какую аннотацию @NotNull использовать в Java?

Программирование на Java предполагает использование различных аннотаций, которые добавляют дополнительную информацию к коду и помогают в его анализе.

Программирование на Java предполагает использование различных аннотаций, которые добавляют дополнительную информацию к коду и помогают в его анализе. Одной из таких аннотаций является @NotNull . Она используется для указания на то, что определенное поле, переменная или возвращаемое значение метода не должны быть равны null .

public void someMethod(@NotNull String string) < // код метода >

В этом примере аннотация @NotNull указывает, что метод someMethod не должен вызываться с null в качестве аргумента.

Однако, в Java существует множество различных реализаций этой аннотации, и выбор одной из них может быть затруднительным. Возникает вопрос: какую из них выбрать?

Варианты аннотаций @NotNull

  1. javax.validation.constraints.NotNull — создана для проверки значений во время выполнения программы, не используется для статического анализа кода.
  2. edu.umd.cs.findbugs.annotations.NonNull — используется статическим анализатором кода FindBugs и его преемником SpotBugs, а также инструментом Sonarqube.
  3. javax.annotation.Nonnull — может работать с FindBugs, однако соответствующий стандарт JSR-305 находится в неактивном состоянии.
  4. org.jetbrains.annotations.NotNull — используется средой разработки IntelliJ IDEA для статического анализа кода.
  5. lombok.NonNull — используется для управления генерацией кода в проекте Lombok. Это временная аннотация, поскольку нет универсального стандарта.
  6. androidx.annotation.NonNull — аннотация, доступная в Android, предоставляемая пакетом аннотаций.
  7. org.eclipse.jdt.annotation.NonNull — используется средой разработки Eclipse для статического анализа кода.

Выбор аннотации

Выбор конкретной аннотации зависит от конкретного проекта и используемых инструментов. Если проект разрабатывается в IntelliJ IDEA, то лучше всего использовать org.jetbrains.annotations.NotNull . Если же проект предполагает использование FindBugs или SpotBugs, то стоит выбрать edu.umd.cs.findbugs.annotations.NonNull .

Однако, стоит помнить, что некоторые из этих аннотаций могут быть несовместимы друг с другом, и их совместное использование может привести к проблемам при анализе кода. В любом случае, выбор аннотации должен быть обоснованным и согласованным с требованиями и условиями конкретного проекта.

Источник

Оцените статью