使用插件生成protobuf
1.在项目的根build.gradle里面 buildscript -> dependencies节点, 引入protobuf-gradle-plugin
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.10'
在app里module的build.gradle 添加 apply plugin: 'com.google.protobuf'
添加依赖: implementation 'com.google.protobuf:protoc:3.5.1'
android->sourceSets节点指定目录
/// 应用com.google.protobuf
apply plugin: 'com.google.protobuf'
android{
sourceSets {
main {
java {
srcDir 'src/main/java'
}
resources {
srcDir 'src/main/proto'//这里main下面存放.proto文件的目录名称不能为protobuf
}
}
}
}
protobuf{
protoc{
artifact = 'com.google.protobuf:protoc:3.5.1'
}
//这里配置生成目录,编译后会在build的目录下生成对应的java文件
generateProtoTasks {
all().each { task ->
task.builtins {
remove java
}
task.builtins {
java {}
}
}
}
}
dependencies {
implementation 'com.google.protobuf:protobuf-java:3.5.1'
}
写.proto文件用来生成Java bean类
//示例
syntax = "proto3";
package com.example.ma.proto;
option java_package = "com.example.ma.proto";
option java_outer_classname = "Students";
option csharp_namespace = "android";
message Student{
string name = 1;
int32 id = 2;
string email = 3;
enum PhoneType{
MOBILE = 0;
WORK = 1;
HOME = 2;
}
message PhoneNumber{
string number = 1;
PhoneType type = 2;
}
repeated PhoneNumber phone = 4; //数组
}
通过以上配置就能自动生成所需要的Java类了。
网友评论