前文介紹了在Android環境中內建,因為需要對序列化資料檔案進行反序列化,是以需要一個java腳本,是以才有了此文,基于IDEA+Gradle內建proto網上也有很簡便介紹,直接在IDEA中添加proto插件即可,但怕有版本問題,影響後面反序列化,白折騰,故想自己添加,下面都介紹
一、添加IDEA插件方式內建
在IDEA中依次點選"File"-->"Settings"-->"Plugins"-->"Browse repositories"後,輸入Protobuf,找到Protobuf Support後安裝重新開機IDEA即可,*.proto檔案将會支援高亮文法顯示,此方法網上案例很多,不過多介紹
可參考:
https://www.cnblogs.com/liugh/p/7505533.html二、手動添加版本內建
1. 建立Gradle項目
以正常方式在IDEA建立一個Gradle項目即可
2. 項目build.gradle配置
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.10'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
plugins {
id 'java'
}
apply plugin: 'application'
apply plugin: 'com.google.protobuf'
group 'cn.starcart'
version '1.0.1'
sourceCompatibility = 1.8
mainClassName = 'cn.starcart.Main'
sourceSets {
main {
java {
srcDirs 'src/main/java', 'src/generated/main/java'
}
proto {
srcDir 'src/main/proto' //指定.proto檔案路徑
}
}
}
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.8.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
java {
option "lite"
}
}
}
}
//生成目錄
generatedFilesBaseDir = "$projectDir/src/generated"
}
repositories {
mavenCentral()
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'com.google.protobuf', name: 'protobuf-java', version: '3.8.0'
}
3. 如上gradle檔案配置,在src/main下增加proto目錄,存放.proto檔案

4. build項目或者執行gradle的build任務即可在src目錄下生成generated目錄,對應proto檔案生成java實體類
其他介紹
proto3文法定義:
https://developers.google.com/protocol-buffers/docs/proto3proto3和proto2的差別參考:
http://www.cppblog.com/sunicdavy/archive/2016/01/25/212739.html