首先用maven建立一個簡單的Java application.
mvn archetype:generate -DgroupId=org.freebird.protocolbuffer -DartifactId=sample -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
建立的目錄結構如下:
$ tree samplesample├── pom.xml└── src ├── main │ └── java │ └── org │ └── freebird │ └── protocolbuffer │ └── App.java └── test └── java └── org └── freebird └── protocolbuffer └── AppTest.java
由於之前Protocol buffer編譯器產生的Java檔案是外部的,因此需要一個plugin協助加入到這個項目中來。
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>../../../template/java</source> </sources> </configuration> </execution> </executions> </plugin>
並且之前的編譯的protocol buffer的java庫已經部署在自己的nexus私服上,現在可以使用dependency來引用它。
<dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>2.4.1</version> </dependency>
現在來實現簡單的Java程式。從參數指定的檔案讀取資料,還原序列化成User對象。
package org.freebird.protocolbuffer;import org.freebird.sample.UserProto.User;import java.io.FileInputStream;import java.io.IOException;/** * Sample! * */public class App { public static void main( String[] args ) throws IOException { System.out.println( "Welcome to the Java sample for protocol buffer!" );User user = User.parseFrom(new FileInputStream(args[0]));System.out.println(user.getName());System.out.println(user.getEmail()); }}
運行下面的命令(我假定你會使用exec plugin)
mvn clean compilemvn exec:java
結果如下:
Welcome to the Java sample for protocol buffer!freebirdshu_chen@esri.com
因此,protocol buffer的跨語言特性相當好用。