如何使用Gradle构建Google协议缓冲区和Kotlin? [英] How to build Google protocol buffers and Kotlin using Gradle?

查看:71
本文介绍了如何使用Gradle构建Google协议缓冲区和Kotlin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个使用Google协议缓冲区和使用Gradle的Kotlin的项目.我希望将原始文件编译成Java源代码,然后从我的Kotlin代码中调用它.

I'm trying to build a project that uses both Google protocol buffers and Kotlin using Gradle. I want the proto files to compile into Java source, which is then called from my Kotlin code.

我的源文件是这样排列的:

My source files are arranged like this:

src/main/proto/*.proto
src/main/kotlin/*.kt
src/test/kotlin/*.kt

这是我的build.gradle文件:

version '1.0-SNAPSHOT'

apply plugin: 'kotlin'
apply plugin: 'java'
apply plugin: 'com.google.protobuf'

repositories {
    mavenCentral()
    maven { url "http://dl.bintray.com/kotlin/kotlin-eap-1.1" }
}


buildscript {
    ext.kotlin_version = '1.1-M02'

    repositories {
        mavenCentral()
        maven { url "http://dl.bintray.com/kotlin/kotlin-eap-1.1" }
    }

    dependencies {
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.0.0'
    }
}

dependencies {
    compile 'com.google.protobuf:protobuf-java:3.0.0'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    testCompile 'junit:junit:4.12'
}

运行./gradlew assemble时,在:compileKotlin期间出现一堆"Unresolved reference"错误.之后,我看到没有生成Java源文件,因此似乎根本没有调用proto编译器.

When I run ./gradlew assemble I get a bunch of "Unresolved reference" errors during :compileKotlin. Afterwards I can see that there are no Java source files generated, so it appears that the proto compiler is not being invoked at all.

如果删除apply plugin: 'kotlin'行,则./gradlew assemble成功生成Java源代码,但是我的Kotlin源代码当然不会编译.

If I remove the apply plugin: 'kotlin' line, then ./gradlew assemble successfully generates the Java source, but of course my Kotlin source is never compiled.

如何修复build.gradle,以便可以从Kotlin调用protobuf代码?

How do I fix my build.gradle so that I can call my protobuf code from Kotlin?

推荐答案

我能够通过在build.gradle中添加两行来使其工作.

I was able to get this to work by adding two lines to my build.gradle.

第一行将proto编译器在其中生成Java代码的目录添加到:compileKotlin查找Java源代码的目录中:

The first line adds the directory in which the proto compiler generates Java code to the directories the :compileKotlin looks for Java source:

sourceSets.main.java.srcDirs += 'build/generated/source/proto/main/java'

第二个确保在调用:compileKotlin之前(重新)生成了Java代码:

The second ensures that the Java code is (re)generated before invoking :compileKotlin:

compileKotlin.dependsOn ':generateProto'

这篇关于如何使用Gradle构建Google协议缓冲区和Kotlin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆