【问题标题】:Generate Protobuf java files with Square's Wire使用 Square 的 Wire 生成 Protobuf java 文件
【发布时间】:2016-03-04 01:51:02
【问题描述】:

我正在尝试从存储在 Android Studio 的 SRC 文件夹下的 .proto 文件生成 .java 文件。我将以下代码放在我的 gradle 文件中,但它似乎不起作用

apply plugin: 'com.squareup.wire'

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'com.squareup.wire:wire-maven-plugin:2.1.1'
  }
}

【问题讨论】:

    标签: android android-gradle-plugin build.gradle maven-plugin square


    【解决方案1】:

    这里有一个 gradle 插件:https://github.com/square/wire-gradle-plugin。然而,黄金时段似乎是not quite ready。我在让它工作时遇到了一些麻烦。

    但是,这里有一种方法可以直接使用线编译器和一个简单的 gradle 任务从 *.proto 文件自动生成 java 代码。我在下面提供了一个 sn-p,其中包含对您的 build.gradle 的修改。根据您的源布局更改 protoPath 和 wireGeneratedPath。

    def protoPath = 'src/proto'
    def wireGeneratedPath = 'build/generated/source/wire'
    
    buildscript {
        repositories {
            mavenCentral()
        }
    
        dependencies {
            classpath 'com.squareup.wire:wire-compiler:2.2.0'
        }
    }
    
    android {
        sourceSets {
            main {
                java {
                    include wireGeneratedPath
                }
            }
        }
    }
    
    dependencies {
        compile 'com.squareup.wire:wire-runtime:2.2.0'
        // Leave this out if you're not doing integration testing...
        androidTestCompile 'com.squareup.wire:wire-runtime:2.2.0'
    }
    
    // This handles the protocol buffer generation with wire
    task generateWireClasses {
        description = 'Generate Java classes from protocol buffer (.proto) schema files for use with squareup\'s wire library'
        delete(wireGeneratedPath)
        fileTree(dir: protoPath, include: '**/*.proto').each { File file ->
            doLast {
                javaexec {
                    main = 'com.squareup.wire.WireCompiler'
                    classpath = buildscript.configurations.classpath
                    args = ["--proto_path=${protoPath}", "--java_out=${wireGeneratedPath}", "${file}"]
                }
            }
        }
    }
    
    preBuild.dependsOn generateWireClasses
    

    【讨论】:

      【解决方案2】:

      所以我最终没有使用 gradle 插件,而是使用了方线编译器 jar。步骤如下。

      1. http://search.maven.org/#artifactdetails%7Ccom.squareup.wire%7Cwire-compiler%7C2.1.1%7Cjar 下载带有依赖项的编译器jar
      2. 将jar文件放入android app根目录
      3. 转到目录并粘贴此命令

        java -jar wire-compiler-2.1.1-jar-with-dependencies.jar --proto_path=directory-of-protofile --java_out=app/src/main/java/ name-of-file.proto
        

      应该可以。确保将 directory-of-protofilename-of-file 替换为您拥有的任何内容。

      【讨论】:

      • 哪个目录?你能简单解释一下吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多