java之序列化與反序列化

  一、這裏主要是介紹Protobuf提供的序列化與反序列化的高效性。相對於傳統的java提供的序列化來講,Protobuf的效率提升了不少倍。可是也有不足的地方,就是proto在對象序列化的時候拋棄了不少數據。好比:類的相關屬性。只保留了數據部分。提升了傳輸的效率,減小帶寬的佔用。java

  二、java的序列化和反序列化app

  1)對象ide

import java.io.Serializable;

public class User implements Serializable{

    private String id;
    private String name;
    private String age;

    public User(String id, String name, String age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Usr{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

  2)序列化和反序列化工具

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;

public class UserSerializable {

    public static void main(String[] args) {
        try {
            //序列化
            User user = new User("1","user","25");
            //序列化字節流
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            //對象讀取
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(user);
            //轉換成字節
            byte[] bytes = byteArrayOutputStream.toByteArray();
            System.out.println(Arrays.toString(bytes));
            //反序列化
            //直接讀取直接,用對象輸入流直接讀取出來
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            //讀取後轉成對應對象
            User u = (User) objectInputStream.readObject();
            System.out.println(u.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  3)效果(目的對比)ui

[-84, -19, 0, 5, 115, 114, 0, 30, 99, 111, 109, 46, 116, 114, 111, 121, 46, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 46, 106, 97, 118, 97, 46, 85, 115, 101, 114, 122, 36, 125, -10, 11, 54, -23, 51, 2, 0, 3, 76, 0, 3, 97, 103, 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 76, 0, 2, 105, 100, 113, 0, 126, 0, 1, 76, 0, 4, 110, 97, 109, 101, 113, 0, 126, 0, 1, 120, 112, 116, 0, 2, 50, 53, 116, 0, 1, 49, 116, 0, 4, 117, 115, 101, 114]
Usr{id='1', name='user', age='25'}

  三、Protobuf的使用this

  1)protoc.exe下載:https://pan.baidu.com/s/1gfaULwv 目的:這個主要是用來建立反序列化的Java文件google

  2)proto文件編碼

  編寫一個.proto爲後綴的文件,文件內容以下:spa

option java_package = "com.troy.application.proto";
option java_outer_classname = "UsrProto";
message Usr{
    required string id = 1;
    required string name = 2;
    required string age = 3;
}

  說明:java_package class裏面的package;java_outer_classname爲輸出類的名稱;message能夠當成class看;required要求必填;prototype

  下面是具體java對應message的寫法。

.proto類型

Java 類型

C++類型

備註

double

double

double

 

float

float

float

 

int32

int

int32

使用可變長編碼方式。編碼負數時不夠高效——若是你的字段可能含有負數,那麼請使用sint32。

int64

long

int64

使用可變長編碼方式。編碼負數時不夠高效——若是你的字段可能含有負數,那麼請使用sint64。

sint32

int

int32

使用可變長編碼方式。有符號的整型值。編碼時比一般的int32高效。

sint64

long

int64

使用可變長編碼方式。有符號的整型值。編碼時比一般的int64高效。

fixed32

int

uint32

老是4個字節。若是數值老是比老是比228大的話,這個類型會比uint32高效。

fixed64

long

uint64

老是8個字節。若是數值老是比老是比256大的話,這個類型會比uint64高效。

sfixed32

int

int32

老是4個字節。

fixed64

long

int64

老是8個字節。

bool

boolean

bool

 

string

String

string

一個字符串必須是UTF-8編碼或者7-bit ASCII編碼的文本。

bytes

ByteString

string

可能包含任意順序的字節數據。

  3)生成Java序列化代碼

  將.proto文件和protoc.exe 放在同一文件夾

  

   而後編寫一個bat文件,或者用cmd命令執行

protoc ./user.proto --java_out=./

  最後會在當前目錄生成一個文件

 

  將包裏面的java文件拷到對應包下面就可使用了

   4)proto的序列化和反序列化

  a、對象(爲了檢測序列化多少,採用同一個對象只是改了一下名稱)

import java.io.Serializable;

public class Usr implements Serializable{

    private String id;
    private String name;
    private String age;

    public Usr(String id, String name, String age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Usr{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

  b、proto序列化文件

public final class UsrProto {
  private UsrProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
  }
  public interface UsrOrBuilder extends
      // @@protoc_insertion_point(interface_extends:Usr)
      com.google.protobuf.MessageOrBuilder {

    /**
     * <code>required string id = 1;</code>
     */
    boolean hasId();
    /**
     * <code>required string id = 1;</code>
     */
    String getId();
    /**
     * <code>required string id = 1;</code>
     */
    com.google.protobuf.ByteString
        getIdBytes();

    /**
     * <code>required string name = 2;</code>
     */
    boolean hasName();
    /**
     * <code>required string name = 2;</code>
     */
    String getName();
    /**
     * <code>required string name = 2;</code>
     */
    com.google.protobuf.ByteString
        getNameBytes();

    /**
     * <code>required string age = 3;</code>
     */
    boolean hasAge();
    /**
     * <code>required string age = 3;</code>
     */
    String getAge();
    /**
     * <code>required string age = 3;</code>
     */
    com.google.protobuf.ByteString
        getAgeBytes();
  }
  /**
   * Protobuf type {@code Usr}
   */
  public  static final class Usr extends
      com.google.protobuf.GeneratedMessage implements
      // @@protoc_insertion_point(message_implements:Usr)
      UsrOrBuilder {
    // Use Usr.newBuilder() to construct.
    private Usr(com.google.protobuf.GeneratedMessage.Builder builder) {
      super(builder);
    }
    private Usr() {
      id_ = "";
      name_ = "";
      age_ = "";
    }

    @Override
    public final com.google.protobuf.UnknownFieldSet
    getUnknownFields() {
      return this.unknownFields;
    }
    private Usr(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      this();
      int mutable_bitField0_ = 0;
      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
          com.google.protobuf.UnknownFieldSet.newBuilder();
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            default: {
              if (!parseUnknownField(input, unknownFields,
                                     extensionRegistry, tag)) {
                done = true;
              }
              break;
            }
            case 10: {
              com.google.protobuf.ByteString bs = input.readBytes();
              bitField0_ |= 0x00000001;
              id_ = bs;
              break;
            }
            case 18: {
              com.google.protobuf.ByteString bs = input.readBytes();
              bitField0_ |= 0x00000002;
              name_ = bs;
              break;
            }
            case 26: {
              com.google.protobuf.ByteString bs = input.readBytes();
              bitField0_ |= 0x00000004;
              age_ = bs;
              break;
            }
          }
        }
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.setUnfinishedMessage(this);
      } catch (java.io.IOException e) {
        throw new com.google.protobuf.InvalidProtocolBufferException(
            e.getMessage()).setUnfinishedMessage(this);
      } finally {
        this.unknownFields = unknownFields.build();
        makeExtensionsImmutable();
      }
    }
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return UsrProto.internal_static_Usr_descriptor;
    }

    protected FieldAccessorTable
        internalGetFieldAccessorTable() {
      return UsrProto.internal_static_Usr_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              Usr.class, Builder.class);
    }

    public static final com.google.protobuf.Parser<Usr> PARSER =
        new com.google.protobuf.AbstractParser<Usr>() {
      public Usr parsePartialFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return new Usr(input, extensionRegistry);
      }
    };

    @Override
    public com.google.protobuf.Parser<Usr> getParserForType() {
      return PARSER;
    }

    private int bitField0_;
    public static final int ID_FIELD_NUMBER = 1;
    private Object id_;
    /**
     * <code>required string id = 1;</code>
     */
    public boolean hasId() {
      return ((bitField0_ & 0x00000001) == 0x00000001);
    }
    /**
     * <code>required string id = 1;</code>
     */
    public String getId() {
      Object ref = id_;
      if (ref instanceof String) {
        return (String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          id_ = s;
        }
        return s;
      }
    }
    /**
     * <code>required string id = 1;</code>
     */
    public com.google.protobuf.ByteString
        getIdBytes() {
      Object ref = id_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (String) ref);
        id_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    public static final int NAME_FIELD_NUMBER = 2;
    private Object name_;
    /**
     * <code>required string name = 2;</code>
     */
    public boolean hasName() {
      return ((bitField0_ & 0x00000002) == 0x00000002);
    }
    /**
     * <code>required string name = 2;</code>
     */
    public String getName() {
      Object ref = name_;
      if (ref instanceof String) {
        return (String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          name_ = s;
        }
        return s;
      }
    }
    /**
     * <code>required string name = 2;</code>
     */
    public com.google.protobuf.ByteString
        getNameBytes() {
      Object ref = name_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (String) ref);
        name_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    public static final int AGE_FIELD_NUMBER = 3;
    private Object age_;
    /**
     * <code>required string age = 3;</code>
     */
    public boolean hasAge() {
      return ((bitField0_ & 0x00000004) == 0x00000004);
    }
    /**
     * <code>required string age = 3;</code>
     */
    public String getAge() {
      Object ref = age_;
      if (ref instanceof String) {
        return (String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          age_ = s;
        }
        return s;
      }
    }
    /**
     * <code>required string age = 3;</code>
     */
    public com.google.protobuf.ByteString
        getAgeBytes() {
      Object ref = age_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (String) ref);
        age_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    private byte memoizedIsInitialized = -1;
    public final boolean isInitialized() {
      byte isInitialized = memoizedIsInitialized;
      if (isInitialized == 1) return true;
      if (isInitialized == 0) return false;

      if (!hasId()) {
        memoizedIsInitialized = 0;
        return false;
      }
      if (!hasName()) {
        memoizedIsInitialized = 0;
        return false;
      }
      if (!hasAge()) {
        memoizedIsInitialized = 0;
        return false;
      }
      memoizedIsInitialized = 1;
      return true;
    }

    public void writeTo(com.google.protobuf.CodedOutputStream output)
                        throws java.io.IOException {
      getSerializedSize();
      if (((bitField0_ & 0x00000001) == 0x00000001)) {
        output.writeBytes(1, getIdBytes());
      }
      if (((bitField0_ & 0x00000002) == 0x00000002)) {
        output.writeBytes(2, getNameBytes());
      }
      if (((bitField0_ & 0x00000004) == 0x00000004)) {
        output.writeBytes(3, getAgeBytes());
      }
      unknownFields.writeTo(output);
    }

    private int memoizedSerializedSize = -1;
    public int getSerializedSize() {
      int size = memoizedSerializedSize;
      if (size != -1) return size;

      size = 0;
      if (((bitField0_ & 0x00000001) == 0x00000001)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(1, getIdBytes());
      }
      if (((bitField0_ & 0x00000002) == 0x00000002)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(2, getNameBytes());
      }
      if (((bitField0_ & 0x00000004) == 0x00000004)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(3, getAgeBytes());
      }
      size += unknownFields.getSerializedSize();
      memoizedSerializedSize = size;
      return size;
    }

    private static final long serialVersionUID = 0L;
    public static Usr parseFrom(
        com.google.protobuf.ByteString data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static Usr parseFrom(
        com.google.protobuf.ByteString data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static Usr parseFrom(byte[] data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static Usr parseFrom(
        byte[] data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static Usr parseFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static Usr parseFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }
    public static Usr parseDelimitedFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input);
    }
    public static Usr parseDelimitedFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input, extensionRegistry);
    }
    public static Usr parseFrom(
        com.google.protobuf.CodedInputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static Usr parseFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }

    public static Builder newBuilder() { return new Builder(); }
    public Builder newBuilderForType() { return newBuilder(); }
    public static Builder newBuilder(Usr prototype) {
      return newBuilder().mergeFrom(prototype);
    }
    public Builder toBuilder() { return newBuilder(this); }

    @Override
    protected Builder newBuilderForType(
        BuilderParent parent) {
      Builder builder = new Builder(parent);
      return builder;
    }
    /**
     * Protobuf type {@code Usr}
     */
    public static final class Builder extends
        com.google.protobuf.GeneratedMessage.Builder<Builder> implements
        // @@protoc_insertion_point(builder_implements:Usr)
        UsrOrBuilder {
      public static final com.google.protobuf.Descriptors.Descriptor
          getDescriptor() {
        return UsrProto.internal_static_Usr_descriptor;
      }

      protected FieldAccessorTable
          internalGetFieldAccessorTable() {
        return UsrProto.internal_static_Usr_fieldAccessorTable
            .ensureFieldAccessorsInitialized(
                Usr.class, Builder.class);
      }

      // Construct using com.troy.application.proto.UsrProto.Usr.newBuilder()
      private Builder() {
        maybeForceBuilderInitialization();
      }

      private Builder(
          BuilderParent parent) {
        super(parent);
        maybeForceBuilderInitialization();
      }
      private void maybeForceBuilderInitialization() {
        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
        }
      }
      public Builder clear() {
        super.clear();
        id_ = "";
        bitField0_ = (bitField0_ & ~0x00000001);
        name_ = "";
        bitField0_ = (bitField0_ & ~0x00000002);
        age_ = "";
        bitField0_ = (bitField0_ & ~0x00000004);
        return this;
      }

      public com.google.protobuf.Descriptors.Descriptor
          getDescriptorForType() {
        return UsrProto.internal_static_Usr_descriptor;
      }

      public Usr getDefaultInstanceForType() {
        return Usr.getDefaultInstance();
      }

      public Usr build() {
        Usr result = buildPartial();
        if (!result.isInitialized()) {
          throw newUninitializedMessageException(result);
        }
        return result;
      }

      public Usr buildPartial() {
        Usr result = new Usr(this);
        int from_bitField0_ = bitField0_;
        int to_bitField0_ = 0;
        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
          to_bitField0_ |= 0x00000001;
        }
        result.id_ = id_;
        if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
          to_bitField0_ |= 0x00000002;
        }
        result.name_ = name_;
        if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
          to_bitField0_ |= 0x00000004;
        }
        result.age_ = age_;
        result.bitField0_ = to_bitField0_;
        onBuilt();
        return result;
      }

      public Builder mergeFrom(com.google.protobuf.Message other) {
        if (other instanceof Usr) {
          return mergeFrom((Usr)other);
        } else {
          super.mergeFrom(other);
          return this;
        }
      }

      public Builder mergeFrom(Usr other) {
        if (other == Usr.getDefaultInstance()) return this;
        if (other.hasId()) {
          bitField0_ |= 0x00000001;
          id_ = other.id_;
          onChanged();
        }
        if (other.hasName()) {
          bitField0_ |= 0x00000002;
          name_ = other.name_;
          onChanged();
        }
        if (other.hasAge()) {
          bitField0_ |= 0x00000004;
          age_ = other.age_;
          onChanged();
        }
        this.mergeUnknownFields(other.unknownFields);
        onChanged();
        return this;
      }

      public final boolean isInitialized() {
        if (!hasId()) {
          
          return false;
        }
        if (!hasName()) {
          
          return false;
        }
        if (!hasAge()) {
          
          return false;
        }
        return true;
      }

      public Builder mergeFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        Usr parsedMessage = null;
        try {
          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
          parsedMessage = (Usr) e.getUnfinishedMessage();
          throw e;
        } finally {
          if (parsedMessage != null) {
            mergeFrom(parsedMessage);
          }
        }
        return this;
      }
      private int bitField0_;

      private Object id_ = "";
      /**
       * <code>required string id = 1;</code>
       */
      public boolean hasId() {
        return ((bitField0_ & 0x00000001) == 0x00000001);
      }
      /**
       * <code>required string id = 1;</code>
       */
      public String getId() {
        Object ref = id_;
        if (!(ref instanceof String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          String s = bs.toStringUtf8();
          if (bs.isValidUtf8()) {
            id_ = s;
          }
          return s;
        } else {
          return (String) ref;
        }
      }
      /**
       * <code>required string id = 1;</code>
       */
      public com.google.protobuf.ByteString
          getIdBytes() {
        Object ref = id_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (String) ref);
          id_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>required string id = 1;</code>
       */
      public Builder setId(
          String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000001;
        id_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>required string id = 1;</code>
       */
      public Builder clearId() {
        bitField0_ = (bitField0_ & ~0x00000001);
        id_ = getDefaultInstance().getId();
        onChanged();
        return this;
      }
      /**
       * <code>required string id = 1;</code>
       */
      public Builder setIdBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000001;
        id_ = value;
        onChanged();
        return this;
      }

      private Object name_ = "";
      /**
       * <code>required string name = 2;</code>
       */
      public boolean hasName() {
        return ((bitField0_ & 0x00000002) == 0x00000002);
      }
      /**
       * <code>required string name = 2;</code>
       */
      public String getName() {
        Object ref = name_;
        if (!(ref instanceof String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          String s = bs.toStringUtf8();
          if (bs.isValidUtf8()) {
            name_ = s;
          }
          return s;
        } else {
          return (String) ref;
        }
      }
      /**
       * <code>required string name = 2;</code>
       */
      public com.google.protobuf.ByteString
          getNameBytes() {
        Object ref = name_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (String) ref);
          name_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>required string name = 2;</code>
       */
      public Builder setName(
          String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000002;
        name_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>required string name = 2;</code>
       */
      public Builder clearName() {
        bitField0_ = (bitField0_ & ~0x00000002);
        name_ = getDefaultInstance().getName();
        onChanged();
        return this;
      }
      /**
       * <code>required string name = 2;</code>
       */
      public Builder setNameBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000002;
        name_ = value;
        onChanged();
        return this;
      }

      private Object age_ = "";
      /**
       * <code>required string age = 3;</code>
       */
      public boolean hasAge() {
        return ((bitField0_ & 0x00000004) == 0x00000004);
      }
      /**
       * <code>required string age = 3;</code>
       */
      public String getAge() {
        Object ref = age_;
        if (!(ref instanceof String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          String s = bs.toStringUtf8();
          if (bs.isValidUtf8()) {
            age_ = s;
          }
          return s;
        } else {
          return (String) ref;
        }
      }
      /**
       * <code>required string age = 3;</code>
       */
      public com.google.protobuf.ByteString
          getAgeBytes() {
        Object ref = age_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (String) ref);
          age_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>required string age = 3;</code>
       */
      public Builder setAge(
          String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000004;
        age_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>required string age = 3;</code>
       */
      public Builder clearAge() {
        bitField0_ = (bitField0_ & ~0x00000004);
        age_ = getDefaultInstance().getAge();
        onChanged();
        return this;
      }
      /**
       * <code>required string age = 3;</code>
       */
      public Builder setAgeBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000004;
        age_ = value;
        onChanged();
        return this;
      }

      // @@protoc_insertion_point(builder_scope:Usr)
    }

    // @@protoc_insertion_point(class_scope:Usr)
    private static final Usr defaultInstance;static {
      defaultInstance = new Usr();
    }

    public static Usr getDefaultInstance() {
      return defaultInstance;
    }

    public Usr getDefaultInstanceForType() {
      return defaultInstance;
    }

  }

  private static final com.google.protobuf.Descriptors.Descriptor
    internal_static_Usr_descriptor;
  private static
    com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internal_static_Usr_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    String[] descriptorData = {
      "\n\nuser.proto\",\n\003Usr\022\n\n\002id\030\001 \002(\t\022\014\n\004name\030" +
      "\002 \002(\t\022\013\n\003age\030\003 \002(\tB&\n\032com.troy.applicati" +
      "on.protoB\010UsrProto"
    };
    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
        new com.google.protobuf.Descriptors.FileDescriptor.    InternalDescriptorAssigner() {
          public com.google.protobuf.ExtensionRegistry assignDescriptors(
              com.google.protobuf.Descriptors.FileDescriptor root) {
            descriptor = root;
            return null;
          }
        };
    com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
        }, assigner);
    internal_static_Usr_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_Usr_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessage.FieldAccessorTable(
        internal_static_Usr_descriptor,
        new String[] { "Id", "Name", "Age", });
  }

  // @@protoc_insertion_point(outer_class_scope)
}
View Code

  c、proto的序列化與反序列化

import java.util.Arrays;

public class UsrSerializable {

    public static void main(String[] args) {
        try {
            //創建工具
            UsrProto.Usr.Builder builder = UsrProto.Usr.newBuilder();
            //設置參數
            builder.setId("1").setName("user").setAge("25");
            //創建對象
            UsrProto.Usr usr = builder.build();
            //序列化
            byte[] bytes = usr.toByteArray();
            System.out.println(Arrays.toString(bytes));

            //反序列化
            UsrProto.Usr u = UsrProto.Usr.parseFrom(bytes);
            System.out.println(u);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  4)結果對比:

[10, 1, 49, 18, 4, 117, 115, 101, 114, 26, 2, 50, 53]
id: "1"
name: "user"
age: "25"

  四、總結

  1)相對於java自己的序列化,proto的序列化精簡了不少不少。

  2)從數據上面來看沒有任何變化,可是proto拋棄了不少東西。

  3)這個在http的數據傳輸上面能夠提升不少效率。

  4)相對來講,編寫上面多作了不少事情,可是考慮數據傳輸等問題能夠採用這種方式!

相關文章
相關標籤/搜索