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?
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
Comments
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
Comments
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].
toString()returns the name of the constant by default. If you are using something that overridestoString, you can get at the name by usingname()instead.enumclass? If so, someone else has overridden yourtoString()method. The behavior is to print the name of the value: docs.oracle.com/javase/6/docs/api/java/lang/Enum.html