Override equals and hashCode for generated Java code?

1,139 views
Skip to first unread message

Kaushal Hooda

unread,
Feb 28, 2018, 8:40:54 AM2/28/18
to Protocol Buffers
Hi,

The default behaviour for equals/hashCode is checking every single field for comparison/generating the hash.

This is problematic for us - we need to override this to use only few fields (e.g., an ID field). Is there any way to do this, apart from editing the generated java code every time I run protoc?

Also, is it possible to generate one .java file for each message type, instead of having them all inside one huge file for the entire schema?

Feng Xiao

unread,
Feb 28, 2018, 7:53:03 PM2/28/18
to Kaushal Hooda, Protocol Buffers
Protobuf generated classes can't be subclassed. I suggest create a wrapper type and implement the hashCode()/equals() there.

To generate one .java file for each message, use "option java_multiple_files = true;" in your .proto file.

--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+u...@googlegroups.com.
To post to this group, send email to prot...@googlegroups.com.
Visit this group at https://groups.google.com/group/protobuf.
For more options, visit https://groups.google.com/d/optout.

Dave Killian

unread,
Mar 7, 2019, 8:53:47 PM3/7/19
to Protocol Buffers
When consumers use equals/hashcodes on the generated classes, new fields can never be added to the messages without breaking consumers at runtime.  Adding new fields is typically how messages (and APIs in gRPC) are safely evolved over time.  So having generated equals/hashcodes seems pretty problematic.  Perhaps hashcodes/equals should fail, or should at least be configurable on the proto definition so that we can generate code that prevents consumers from relying on this.  
Reply all
Reply to author
Forward
0 new messages