How to use name () method in Java enums

I am reviewing the code using the name method Java Enum.

Can someone explain to me how and where to use the name() Enum method in java.

+4
source share
2 answers

Given:

 enum Direction { NORTH("north"), SOUTH("south"), EAST("east"), WEST("west"); private final String printableValue; Direction(String printableValue) { this.printableValue = printableValue; } @Override public String toString() { return printableValue; } } 

then this code:

 Direction travelDirection = Direction.NORTH; System.out.println("I am going " + travelDirection); 

will print

 I am going north 

but this code:

 Direction travelDirection = Direction.NORTH; System.out.println("I am going " + travelDirection.name()); 

will print

 I am going north 
+7
source

The name() method is pretty much similar to toString() , except that it is declared final, so the definition of an enumeration cannot change it. This can be important, for example, when writing a structure for serializing data, where you need to rely on the fact that the enumeration name is one Java identifier that uniquely identifies a constant. There may be a few more applications, but as the manual says:

Most programmers should use the toString() method, preferring this one, since the toString method can return a more convenient name.

In general, I would say that you should use toString() when the output is intended for the human reader, and name() when it targets another process for parsing in some way.

+3
source

All Articles