Représentation String avec Lombox

De EjnTricks

La fonction toString permet d'avoir une représentation en chaîne de caractères de l'instance qui n'est pas très lisible par défaut.

Lombok fournit l'annotation ToString qui permet de reprendre l'ensemble des variables.

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.tostring.


Hand-icon.png Votre avis

Nobody voted on this yet

 You need to enable JavaScript to vote


Add-icon.png Toutes variables

L'utilisation basique de l'annotation ToString permet donc de reprendre le nom et les valeurs des variables dans la chaîne produite. La classe DataObject contient les deux variables suivantes.

  • name;
  • surname.
package fr.ejn.tutorial.java.lombok.tostring;

import lombok.Setter;
import lombok.ToString;

/**
 * Tutorial class to illustrate toString generation on class.
 *
 * @author Etienne Jouvin
 *
 */
@ToString
@Setter
public class DataObject {

  private String name;
  private String surname;

}

A noter que seule l'annotation Setter est utilisée, aucun getter n'est mis à disposition.

Le test unitaire DataObjectTest permet de démontrer la construction de la chaîne avec toutes les variables.

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

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 DataObjectTest {

  @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 testToString() throws Exception {
    DataObject actual = new DataObject();
    actual.setName("data name");
    actual.setSurname("data surname");

    String expected = "DataObject(name=data name, surname=data surname)";
    assertThat(actual.toString()).isEqualTo(expected);
  }

}


Multiples-icon.png Héritage classe

Lorsqu'une classe étend une classe parente, l'annotation peut être configurée pour utiliser ou non les variables parentes lors de la construction de la chaîne. Pour cla, il faut ajouter l'argument callSuper.

La classe ChildDataWithoutSuperObject montre comment n'utiliser que les variables de la classe, et sans la parente, en passant la valeur false à l'argument callSuper.

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

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * Tutorial class to illustrate toString generation with only class variables, and not on parent
 * class variables.
 *
 * @author Etienne Jouvin
 *
 */
@ToString(callSuper = false)
@Getter
@Setter
public class ChildDataWithoutSuperObject extends DataObject {

  private String id;

}

Le test unitaire associé ChildDataWithoutSuperObjectTest confirme le comportement, où seule la valeur de id est utilisée.

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

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 ChildDataWithoutSuperObjectTest {

  @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 testToString() throws Exception {
    ChildDataWithoutSuperObject actual = new ChildDataWithoutSuperObject();
    actual.setName("data name");
    actual.setSurname("data surname");
    actual.setId("data id");

    String expected = "ChildDataWithoutSuperObject(id=data id)";
    assertThat(actual.toString()).isEqualTo(expected);
  }

}

A l'inverse, en spécifiant la valeur true dans l'argument callSuper, les variables de la classe parente sont prises en compte comme cela est implémenté dans la classe ChildDataWithSuperObject.

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

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * Tutorial class to illustrate toString generation with class and parent class variables.
 *
 * @author Etienne Jouvin
 *
 */
@ToString(callSuper = true)
@Getter
@Setter
public class ChildDataWithSuperObject extends DataObject {

  private String id;

}

Le test unitaire associé ChildDataWithSuperObjectTest confirme ce comportement.

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

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 ChildDataWithSuperObjectTest {

  @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 testToString() throws Exception {
    ChildDataWithSuperObject actual = new ChildDataWithSuperObject();
    actual.setName("data name");
    actual.setSurname("data surname");
    actual.setId("data id");

    String expected = "ChildDataWithSuperObject(super=DataObject(name=data name, surname=data surname), id=data id)";
    assertThat(actual.toString()).isEqualTo(expected);
  }

}


Vues-icon.png Sélection variables

Il est également possible de filtrer les variables utilisées, pour éviter d'afficher une variable sensible par exemple. L'argument exclude de l'annotation permet de fournir la liste des variables devant être exclues.

Dans la classe DataWithSpecificFieldsObject, seule la variable id est utilisée et les variables name et surname sont exclues.

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

import lombok.Setter;
import lombok.ToString;

/**
 * Tutorial class to illustrate toString generation based on specific variables.
 *
 * @author Etienne Jouvin
 *
 */
@ToString(exclude = { "name", "surname" })
@Setter
public class DataWithSpecificFieldsObject {

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

}

Dans le test unitaire DataWithSpecificFieldsObjectTest, les variables sont modifiées pour montrer que seule la valeur de id est utilisée.

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

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 DataWithSpecificFieldsObjectTest {

  @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 testToString() throws Exception {
    DataWithSpecificFieldsObject actual = new DataWithSpecificFieldsObject();
    actual.setName("data name");
    actual.setSurname("data surname");
    actual.setId("data id");

    String expected = "DataWithSpecificFieldsObject(id=data id)";
    assertThat(actual.toString()).isEqualTo(expected);
  }

}


Viewer icon.png Voir aussi

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