将对象与许多(私有)变量进行比较的有效方法
我有一个类,其中有一系列类似的私人变量列表,
class ManyVariables {
private int var1;
private int var2;
//....
private int var49;
public int getVar1(){};
public int getVar2(){};
//....
public int getVar49(){};
}
我试图覆盖equals
方法,以便它比较两个实例的所有变量,但是,由于变量列表很长将它们全部输入手动真的不是理想的。有没有办法将它们全部纳入stream
对象并使用stream
的管道进行比较?我知道我还可以使用 feflection>我宁愿不要将私有字段设置为在运行时可访问。谢谢!
I have a class that with a long list of private variables like this
class ManyVariables {
private int var1;
private int var2;
//....
private int var49;
public int getVar1(){};
public int getVar2(){};
//....
public int getVar49(){};
}
I am trying to override the equals
method so that it compares all the variables of two instances, however, since the list of variables is so long typing them all out manually is really not ideal. Is there a way to get them all into a Stream
object and use Stream
's pipeline to do the comparison? I know I can also use reflection but I'd rather not set the private fields to accessible at run time. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因此,您要么构建一种方法,如前所述,通过IDE生成它,要么将其放入JSON对象中并比较字符串。我看不到任何其他方式。
有一些库将您的对象转换为JSON或任何其他字符串格式。甚至ToString()方法也可能起作用。但是要小心,因为最后两个提到的解决方案仅比较简易值。
So you either build a method as you stated earlier, generate it through an IDE or put it inside a JSON object and compare the strings. I do not see any other way.
There are libraries that convert your object into JSON or any other string format. Even the toString() method might work. But be careful as these last 2 mentioned solutions only compare easy values.
.java
类mulanvariables
equals()
中,验证所有字段已被选中(选中所有字段),然后在第二个提示中单击hashcode()
的“ next”这是一个示例,从此类别开始:
使用自动生成后,I有:
.java
file forclass ManyVariables
equals()
, verify all of the fields are checked (check the boxes if any are not already checked), then click "Next"hashCode()
, again verify all fields are checked, then "Finish"Here's an example, starting with this class:
After using the automatic generation, I have this: