Proto编译报错:LazyStringArrayList.emptyList()无法访问的解决办法
修复Protobuf生成代码中LazyStringArrayList.emptyList()访问权限错误
问题详情
Proto 文件定义
repeated string applicableType = 4;
生成的Java代码
applicableType_ = com.google.protobuf.LazyStringArrayList.emptyList();
编译错误信息
emptyList() is not public in LazyStringArrayList; cannot be accessed from outside package com.google.protobuf.LazyStringArrayList.emptyList();
构建失败,已尝试切换Java 17/19版本、重新生成Proto文件,问题仍存在。
修复方案
对齐Protobuf版本
这个错误大概率是代码生成器(protoc)版本和项目依赖的protobuf-java runtime版本不匹配导致的。比如用高版本protoc生成了代码,但项目依赖的runtime版本较低,此时emptyList()方法可能还未被设为公共访问权限。确保protoc版本与项目中protobuf-java依赖的版本完全一致。替换为公共可用的空列表实现
若暂时无法调整版本,可手动修改生成的代码,将LazyStringArrayList.emptyList()替换为LazyStringArrayList.newInstance()(生成空的实例),或者Collections.emptyList()(需确保类型匹配,可强转为List<String>)。注意:手动修改生成代码只是临时方案,长期来看还是要对齐版本避免后续重复问题。检查构建依赖配置
确认项目构建文件(Maven/Gradle)中protobuf相关组件的版本统一:
Maven依赖示例:<dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>统一版本号</version> </dependency>Maven插件示例:
<plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.6.1</version> <configuration> <protocArtifact>com.google.protobuf:protoc:统一版本号:exe:${os.detected.classifier}</protocArtifact> </configuration> </plugin>清理后重新构建
执行构建工具的清理命令(如mvn clean或gradle clean),彻底清除旧的生成文件和构建缓存,再重新生成代码并执行构建。
内容的提问来源于stack exchange,提问作者ShubhamK
相关产品推荐
相关产品推荐

