2013-10-08 223 views
2

我枚舉原始的Java代碼:替換字符串與枚舉枚舉生成自動protobuf的

public enum CarModel { 
    NOMODEL("NOMODEL"); 
    X("X"), 
    XS("XS"), 
    XSI("XS-I"); //NOTE the special - character. Can't be declared XS-I 
    XSI2("XS-I.2"); //NOTE the special . character. Can't be declared XS-I.2 
    private final String carModel; 
    CarModel(String carModel) { 
     this.carModel = carModel; 
    } 

    public String getCarModel() { return carModel; } 

    public static CarModel fromString(String text) { 
     if (text != null) { 
      for (CarModel c : CarModel.values()) { 
       if (text.equals(c.carModel)) { 
        return c; 
       } 
      } 
     } 
     return NOMODEL; //default 
    } 
} 

現在,如果我使用protobuf的,我得到的.proto文件:

enum CarModel { 
    NOMODEL = 0; 
    X = 1; 
    XS = 2; 
    XSI = 3; 
    XSI2 = 4; 
} 

從我earlier question我知道我可以調用由protoc生成的枚舉並刪除我自己的類(從而避免重複的值定義),但我仍然需要定義某處(在包裝類?包裝枚舉類?)備用fromString()方法將返回正確的字符串每枚枚舉。我怎麼做?

編輯: 如何實現如下:

String carModel = CarModel.XSI.toString(); 這將返回 「XS-I」

和:

CarModel carModel = CarModel.fromString("XS-I.2"); 

回答

4

您可以使用Protobuf的"custom options"完成此操作。

import "google/protobuf/descriptor.proto"; 

option java_outer_classname = "MyProto"; 
// By default, the "outer classname" is based on the proto file name. 
// I'm declaring it explicitly here because I use it in the example 
// code below. Note that even if you use the java_multiple_files 
// option, you will need to use the outer classname in order to 
// reference the extension since it is not declared in a class. 

extend google.protobuf.EnumValueOptions { 
    optional string car_name = 50000; 
    // Be sure to read the docs about choosing the number here. 
} 

enum CarModel { 
    NOMODEL = 0 [(car_name) = "NOMODEL"]; 
    X = 1 [(car_name) = "X"]; 
    XS = 2 [(car_name) = "XS"]; 
    XSI = 3 [(car_name) = "XS-I"]; 
    XSI2 = 4 [(car_name) = "XS-I.2"]; 
} 

現在在Java中,你可以這樣做:

String name = 
    CarModel.XSI.getValueDescriptor() 
    .getOptions().getExtension(MyProto.carName); 
assert name.equals("XS-I"); 

https://developers.google.com/protocol-buffers/docs/proto#options(略微向下滾動到自定義選項的部分。)

+0

我試過你的代碼,看起來protoc不會創建getProto()方法,我需要調用它才能將ValueDescriptor轉換爲Extension。有任何想法嗎 ? –

+0

還有一件事 - 當查看生成的java代碼時,「XS-I」和「XS-I.2」字符串出現的唯一位置在最後一個字段中,該字段定義爲:「static {java.lang.String [] descriptorData = {「基本上保存了我的.proto源碼 –

+0

糟糕,對不起,該方法被稱爲'toProto',而不是'getProto'。我會編輯我的答案。 是的,註釋都進入descriptorData。我給出的代碼實際上將它們從那裏提取出來。 –

-1
CarModel carmodel = Enum.valueOf(CarModel.class, "XS") 

CarModel carmodel = CarModel.valueOf("XS"); 
+0

我需要另一個方向:弦模型= CarModel.XSI。的toString();但能夠告訴它XSI轉換爲「XS-I」。還有以下CarModel carModel = CarModel.fromString(「XS-I」); –