Java – Protobuf-generated classes could not be found when using gradle

Protobuf-generated classes could not be found when using gradle… here is a solution to the problem.

Protobuf-generated classes could not be found when using gradle

If I follow the instructions in grpc-java, the readme and the file I generated using maven, protobuf appear in target directory, then in the classpath for me to extend etc. However, when I use Gradle, the generated class appears in the build directory and does not exist in the classpath. I’m still new to Gradle, so I’m not quite sure why it behaves so differently.

My build.gradle file

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

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.5'
    }
}

group 'co.example'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile 'io.grpc:grpc-netty-shaded:1.15.1'
    compile 'io.grpc:grpc-protobuf:1.15.1'
    compile 'io.grpc:grpc-stub:1.15.1'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.5.1-1"
    }
    noinspection GroovyAssignabilityCheck
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.15.1'
        }
    }
    generateProtoTasks {
        all()*.plugins {
            grpc {}
        }
    }
}

Solution

It looks like gradle (if you want to use the generated stub/server interface) in the project where your proto files are located (i.e. the project is not just for generating jars and publishing them) then you need to add generatedFilesBaseDir to your build.gradle file:

protobuf {
    generatedFilesBaseDir = "$projectDir/src/main/java/generated"
    ...
}

Once this is done, the stub should be in your classpath.

public class SomeServer extends MyProtoClassGrpc.PDFExtractImplBase {}

Related Problems and Solutions