Google Protobuf文件转Java文件
Protobuf协议目前分两个版本 protobuf v3 与protobuf v2两个版本
项目中使用Protobuf作为数据传输,使用AndroidStudio工具批量编译protobuf文件比较简单。
开始配置环境
protobuf文件
option java_package = "com.daycodeday.test";
option java_outer_classname = "MtmColWrapper";
message MtmCol {
optional uint32 colnamelength = 1;
required string colname = 2;
optional uint32 coltype = 3;
optional uint32 coltypestringlength = 4;
optional string coltypestring = 5;
optional uint32 length = 6;
optional uint32 precision = 7;
optional uint32 scale = 8;
optional uint32 nullable = 9;
}
项目根目录配置build.gradle
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
// protobuf支持版本
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.0'
}
modle根目录配置build.gradle
//依赖支持
apply plugin: 'com.google.protobuf'
//指定文件目录
sourceSets {
main {
proto {
//main目录新建proto目录
srcDir 'src/main/proto'
include '**/*.proto'
}
java {
srcDir 'src/main/java'
}
}
}
//依赖库
compile 'com.google.protobuf:protobuf-java:2.5.0'
compile 'com.google.protobuf:protoc:2.5.0'
//构建task
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:2.5.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
}
task.builtins {
java {}
// Add cpp output without any option.
// DO NOT omit the braces if you want this builtin to be added.
cpp {}
}
}
}
//生成目录
generatedFilesBaseDir = "$projectDir/src/generated"
}
我使用依赖库是 2.5 ,如果是3.0以上依赖库的需要定义下协议头
3.0 头部开始加上
syntax = "proto3";
2.0 头部加上
syntax = "proto2";
下面是完整的gradle文件
apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.daycodeday.myapplication"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
proto {
srcDir 'src/main/proto'
include '**/*.proto'
}
java {
srcDir 'src/main/java'
}
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.google.protobuf:protobuf-java:3.1.0'
compile 'com.google.protobuf:protoc:3.1.0'
}
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.1.0'
}
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
}
task.builtins {
java {}
// Add cpp output without any option.
// DO NOT omit the braces if you want this builtin to be added.
cpp {}
}
}
}
//生成目录
generatedFilesBaseDir = "$projectDir/src/generated"
}