Constructeurs avec Lombox

De EjnTricks

Lombok permet de générer des builder à l'aide de l'annotation Builder. Mais il est également possible de maîtriser la mise à disposition des constructeurs.

Le code source est disponible à l'adresse suivante: http://www.svn.jouvinio.net/study/trunk/lombok, et en particulier les classes du package fr.ejn.tutorial.java.lombok.constructor.


Hand-icon.png Votre avis

Nobody voted on this yet

 You need to enable JavaScript to vote


Forbidden-icon.png Sans argument

Par défaut, une classe contient le constructeur par défaut sans aucun argument. Lombok permet de spécifier cette mise à disposition à l'aide de l'annotation NoArgsConstructor. Cela n'a pas une grande valeur ajoutée mais est illustré par la classe DataWithNoArgumentConstructorObject.

package fr.ejn.tutorial.java.lombok.constructor;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * Tutorial class to illustrate default constructor generation.
 *
 * @author Etienne Jouvin
 *
 */
@NoArgsConstructor
@Getter
@Setter
public class DataWithNoArgumentConstructorObject {

  private String id;
  private String name;
  private String surname;

}

Les annotations Getter et Setter sont mises en place afin de pouvoir accéder aux variables.

Le test unitaire DataWithBuilderObjectTest illustre l'utilisation du constructeur.

package fr.ejn.tutorial.java.lombok.constructor;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class DataWithNoArgumentConstructorObjectTest {

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
  }

  @Before
  public void setUp() throws Exception {
  }

  @After
  public void tearDown() throws Exception {
  }

  @Test
  public void testConstructor() throws Exception {
    DataWithNoArgumentConstructorObject actual = new DataWithNoArgumentConstructorObject();
    actual.setId("data id");
    actual.setName("data name");
    actual.setSurname("data surname");

    assertThat(actual.getId()).isEqualTo("data id");
    assertThat(actual.getName()).isEqualTo("data name");
    assertThat(actual.getSurname()).isEqualTo("data surname");
  }

}


Add-icon.png Toutes variables

L'annotation AllArgsConstructor permet de générer un constructeur avec toutes les variables de la classe, comme illustré dans la classe DataWithAllArgumentsConstructorObject

package fr.ejn.tutorial.java.lombok.constructor;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * Tutorial class to illustrate constructor generation with all variables.
 *
 * @author Etienne Jouvin
 *
 */
@AllArgsConstructor
@Getter
public class DataWithAllArgumentsConstructorObject {

  private String id;
  private String name;
  private String surname;

}

Dans ce cas, un constructeur est mis à disposition avec trois arguments pour spécifier les variables.

  • id;
  • name;
  • surname.

A noter, l'utilisation de l'annotation Getter afin de générer les getters.

Le test unitaire DataWithAllArgumentsConstructorObjectTest montre l'utilisation de ce constructeur.

package fr.ejn.tutorial.java.lombok.constructor;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class DataWithAllArgumentsConstructorObjectTest {

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
  }

  @Before
  public void setUp() throws Exception {
  }

  @After
  public void tearDown() throws Exception {
  }

  @Test
  public void testConstructor() throws Exception {
    DataWithAllArgumentsConstructorObject actual = new DataWithAllArgumentsConstructorObject("data id", "data name", "data surname");
    
    assertThat(actual.getId()).isEqualTo("data id");
    assertThat(actual.getName()).isEqualTo("data name");
    assertThat(actual.getSurname()).isEqualTo("data surname");
  }

}

A noter que le constructor par défaut, sans argument, n'est pas disponible.


Vues-icon.png Variables obligatoires

Pour cet exemple, l'annotation RequiredArgsConstructor est utilisée afin de générer un constructeur avec les variables ne pouvant être nulle. Dans la classe DataWithRequiredVariableConstructorObject, l'annotation NonNull est ajoutée à la variable id. Le constructeur rendu disponible accepte alors un argument pour spécifier la valeur de id.

package fr.ejn.tutorial.java.lombok.constructor;

import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

/**
 * Tutorial class to illustrate constructor generation with required variables.
 *
 * @author Etienne Jouvin
 *
 */
@RequiredArgsConstructor
@Getter
@Setter
public class DataWithRequiredVariableConstructorObject {

  @NonNull
  private String id;
  private String name;
  private String surname;

}

Le test unitaire DataWithRequiredVariableConstructorObjectTest démontre l'utilisation du constructeur généré.

package fr.ejn.tutorial.java.lombok.constructor;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class DataWithRequiredVariableConstructorObjectTest {

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
  }

  @Before
  public void setUp() throws Exception {
  }

  @After
  public void tearDown() throws Exception {
  }

  @Test
  public void testConstructor() throws Exception {
    DataWithRequiredVariableConstructorObject actual = new DataWithRequiredVariableConstructorObject("data id");
    actual.setName("data name");
    actual.setSurname("data surname");

    assertThat(actual.getId()).isEqualTo("data id");
    assertThat(actual.getName()).isEqualTo("data name");
    assertThat(actual.getSurname()).isEqualTo("data surname");
  }

}


Multiples-icon.png Combinaison constructeurs

Les précédents exemples présentent les trois annotations pour générer les constructeurs. Il est possible de les combiner, mais attention il faut prendre en compte certaines contraintes. Par exemple, il est impossible de combiner les annotations RequiredArgsConstructor et NoArgsConstructor, car des champs seront déclarés comme non null.

La classe DataWithCombineConstructorsObject illustre la combinaire des annotations AllArgsConstructor et NoArgsConstructor.

package fr.ejn.tutorial.java.lombok.constructor;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * Tutorial class to illustrate default constructor and constructor with all variables generation.
 *
 * Can not combine with specific argument, because in this case the no args will fail.
 *
 * @author Etienne Jouvin
 *
 */
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class DataWithCombineConstructorsObject {

  private String id;
  private String name;
  private String surname;

}

Le test unitaire DataWithCombineConstructorsObjectTest démontre l'utilisation des deux constructeurs générés.

package fr.ejn.tutorial.java.lombok.constructor;

import static org.assertj.core.api.Assertions.assertThat;

import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class DataWithCombineConstructorsObjectTest {

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
  }

  @Before
  public void setUp() throws Exception {
  }

  @After
  public void tearDown() throws Exception {
  }

  @Test
  public void testConstructorAllArguments() throws Exception {
    DataWithCombineConstructorsObject actual = new DataWithCombineConstructorsObject("data id", "data name", "data surname");

    Assertions.assertThat(actual.getId()).isEqualTo("data id");
    Assertions.assertThat(actual.getName()).isEqualTo("data name");
    Assertions.assertThat(actual.getSurname()).isEqualTo("data surname");
  }

  @Test
  public void testConstructorNoArgument() throws Exception {
    DataWithCombineConstructorsObject actual = new DataWithCombineConstructorsObject();
    actual.setId("data id");
    actual.setName("data name");
    actual.setSurname("data surname");

    assertThat(actual.getId()).isEqualTo("data id");
    assertThat(actual.getName()).isEqualTo("data name");
    assertThat(actual.getSurname()).isEqualTo("data surname");
  }

}


Viewer icon.png Voir aussi

Documentation officielle: https://projectlombok.org/features/constructor