如何比较 Java 中的两个 proto buffer 消息?
How to compare two proto buffer message in Java?
在包com.google.protobuf
中我找到了一个Message
界面,它声称会比较内容:
public interface Message extends MessageLite, MessageOrBuilder {
// -----------------------------------------------------------------
// Comparison and hashing
/**
* Compares the specified object with this message for equality. Returns
* <tt>true</tt> if the given object is a message of the same type (as
* defined by {@code getDescriptorForType()}) and has identical values for
* all of its fields. Subclasses must implement this; inheriting
* {@code Object.equals()} is incorrect.
*
* @param other object to be compared for equality with this message
* @return <tt>true</tt> if the specified object is equal to this message
*/
@Override
boolean equals(Object other);
但是我写测试代码:
public class Test {
public static void main(String args[]) {
UserMidMessage.UserMid.Builder aBuilder = UserMidMessage.UserMid.newBuilder();
aBuilder.setQuery("aaa");
aBuilder.setCateId("bbb");
aBuilder.setType(UserMidMessage.Type.BROWSE);
System.out.println(aBuilder.build() == aBuilder.build());
}
}
它给出 false
。
那么,如何与 proto 缓冲区消息进行比较?
在Java中,您需要使用equals
方法比较对象,而不是==
运算符。问题是 ==
比较的是同一个对象,而 equals
方法比较的是它们是否与 class 的开发人员提供的实现相等。
System.out.println(aBuilder.build().equals(aBuilder.build()));
有关更多详细信息,已经有很多关于此的问题(例如 Java == vs equals() confusion。
==
比较对象引用,它检查两个操作数是否指向同一个对象(不是等价对象,同一个对象),所以你可以确定.build()
每次都创建一个新对象...
要使用您发布的代码,您必须与 equals
进行比较
System.out.println(aBuilder.build().equals(aBuilder.build()));
在包com.google.protobuf
中我找到了一个Message
界面,它声称会比较内容:
public interface Message extends MessageLite, MessageOrBuilder {
// -----------------------------------------------------------------
// Comparison and hashing
/**
* Compares the specified object with this message for equality. Returns
* <tt>true</tt> if the given object is a message of the same type (as
* defined by {@code getDescriptorForType()}) and has identical values for
* all of its fields. Subclasses must implement this; inheriting
* {@code Object.equals()} is incorrect.
*
* @param other object to be compared for equality with this message
* @return <tt>true</tt> if the specified object is equal to this message
*/
@Override
boolean equals(Object other);
但是我写测试代码:
public class Test {
public static void main(String args[]) {
UserMidMessage.UserMid.Builder aBuilder = UserMidMessage.UserMid.newBuilder();
aBuilder.setQuery("aaa");
aBuilder.setCateId("bbb");
aBuilder.setType(UserMidMessage.Type.BROWSE);
System.out.println(aBuilder.build() == aBuilder.build());
}
}
它给出 false
。
那么,如何与 proto 缓冲区消息进行比较?
在Java中,您需要使用equals
方法比较对象,而不是==
运算符。问题是 ==
比较的是同一个对象,而 equals
方法比较的是它们是否与 class 的开发人员提供的实现相等。
System.out.println(aBuilder.build().equals(aBuilder.build()));
有关更多详细信息,已经有很多关于此的问题(例如 Java == vs equals() confusion。
==
比较对象引用,它检查两个操作数是否指向同一个对象(不是等价对象,同一个对象),所以你可以确定.build()
每次都创建一个新对象...
要使用您发布的代码,您必须与 equals
System.out.println(aBuilder.build().equals(aBuilder.build()));