昨晚20210407一同事问我,为什么protobuf的message获取的列表不可改
原理
经过调试发现List的类型为UnmodifiableList,实现类于java.util.Collections.UnmodifiableList,如其名不可修改。重写的removeif等方法全都直接抛出UnsupportedOperationException
在grpc序列化包中构建为message时对repeated类型转换便是UnmodifiableList
com.google.protobuf.GeneratedMessageV3.Builder#getField
public Object getField(final FieldDescriptor field) {
Object object = internalGetFieldAccessorTable().getField(field).get(this);
if (field.isRepeated()) {
// The underlying list object is still modifiable at this point.
// Make sure not to expose the modifiable list to the caller.
return Collections.unmodifiableList((List) object);
} else {
return object;
}
}
由此解释清楚,设计的时候传输数据便是不可修改的