Skip to content
Advertisement

How to print enum description

Im creating a Java application, I used enum to create movie category. When I input MovieCategory.WAR I would like to see War movie(My description) instead of WAR. How is it possible? I tried MovieCategory.WAR.getDescription() but does’t work.

public enum MovieCategory {
   COMEDY("Comedy"), HORROR("Horror"), SCIFI("Sci-Fi"),
   ACTION("Action movie"), ROMANTIC("Romantic"),
   CLASSIC("Classic"), WAR("War movie");

   private final String description;

   MovieCategory(String description) {
       this.description = description;
   }

   public String getDescription() {
       return description;
   }
}
public class MovieManager {

    private List<Movie> movieList;

    public MovieManager() {
        this.movieList = new ArrayList<>();
        movieList.add(new Movie("Simple movie", MovieCategory.WAR,"Testing description.",167,12));
(...)

Advertisement

Answer

The enum works correctly:

  public static void main(String[] args) {
    // Displays: Comedy
    System.out.println(COMEDY.getDescription());
    // Displays: COMEDY
    System.out.println(COMEDY);
  }

Or, maybe you want the toString method to use description?

public enum MovieCategory {
  COMEDY("Comedy");

  private final String description;

  MovieCategory(String description) {
    this.description = description;
  }

  public String getDescription() {
    return description;
  }

  @Override
  public String toString() {
    return getDescription();
  }

  public static void main(String[] args) {
    // Displays: Comedy
    System.out.println(COMEDY.getDescription());
    // Displays: Comedy
    System.out.println(COMEDY);
  }
}

UPDATE #3: It seems the issue is the JSON response. If you want the description to be returned, you can annotate the getDescription method wtih @JsonValue.

import com.fasterxml.jackson.annotation.JsonValue;

public enum MovieCategory {
  WAR("War movie");

  private final String description;

  MovieCategory(String description) {
    this.description = description;
  }

  @JsonValue
  public String getDescription() {
    return description;
  }

  @Override
  public String toString() {
    return getDescription();
  }

  public static void main(String[] args) {
    // Displays: Comedy
    System.out.println(WAR.getDescription());
    // Displays: Comedy
    System.out.println(WAR);
  }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement