The default toString prints the int value instead of the enum name. Is there an easy way to make it print the enum name instead?
-
1Your first sentence is not correct. `toString()` returns the name of the constant by default. If you are using something that overrides `toString`, you can get at the name by using `name()` instead. – roippi Jul 23 '13 at 01:20
-
1Are you using the `enum` class? If so, someone else has overridden your `toString()` method. The behavior is to print the name of the value: http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html – Jerome Jul 23 '13 at 01:23
-
1To people who are responding, Raymond is probably talking about Enum's in protocol buffers !!! – Bruce Martin Jul 23 '13 at 01:37
-
To @Raymond, please tell us how are you accessing protocol-buffers, When you generate java, it should generate a standard Java-Enum which toString() = Enum-Value. Are you DynamicMessage or Lite-Messages or something other than standard Protocol Buffers. Some code would be useful as well ??? – Bruce Martin Jul 23 '13 at 02:32
3 Answers
(Answer is for proto3)
Use Carl's enum example:
enum Foo {
BAR = 1;
BAZ = 5;
QUX = 1234;
}
Suppose you have variable: Foo foo = Foo.BAR
, to get the name of foo
:
String fooName = foo.getValueDescriptor().getName(); //fooName="BAR"
Also see:
https://developers.google.com/protocol-buffers/docs/reference/java-generated#enum

- 1,057
- 11
- 17
For the following protobuf enum:
enum Foo {
BAR = 1;
BAZ = 5;
QUX = 1234;
}
The docs say that:
An integer constant is also generated with the suffix _VALUE for each enum value.
It sounds like you are using the the constant "e.g. BAR_VALUE, BAZ_VALUE, or QUX_VALUE". Is this the case?
See: https://developers.google.com/protocol-buffers/docs/reference/java-generated#enum

- 5,970
- 1
- 28
- 37
You could get a list of the enum values using .values()
in java.
Assuming you had a protobuf enum
enum Foo {
BAR = 1;
BAZ = 2;
}
If you referenced Foo from Java, you could get an array of Foo's values with Foo.values()
- or if you were using a generic enum for the call, genericEnum.getDeclaringClass().getEnumConstants()
.
This would give you [BAR, BAZ]
.

- 134
- 1
- 3