6

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?

4
  • 1
    Your 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. Commented Jul 23, 2013 at 1:20
  • 1
    Are you using the enum class? If so, someone else has overridden your toString() method. The behavior is to print the name of the value: docs.oracle.com/javase/6/docs/api/java/lang/Enum.html Commented Jul 23, 2013 at 1:23
  • 1
    To people who are responding, Raymond is probably talking about Enum's in protocol buffers !!! Commented Jul 23, 2013 at 1: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 ??? Commented Jul 23, 2013 at 2:32

3 Answers 3

7

(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

https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Descriptors.EnumDescriptor#getName()

Sign up to request clarification or add additional context in comments.

Comments

0

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

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.