如何更新 Java 构造函数、等于、哈希等。在日食中?
我想知道是否有人知道由 Eclipse 在 Java 中生成的更新、构造函数、等于、哈希、字符串等的好方法。 很多时候,在使用自动生成的代码存根之后,我向类添加一个成员变量,然后我需要删除自动生成的代码,然后重新做一遍。 有没有办法让 Eclipse 将新变量添加到自动生成的代码存根中?
编辑:好的删除不是必需的,但是我仍然必须去生成它们中的每一个,我正在寻找一个自动解决方案。
I wanted to know if anyone knows about a good way to update,constructors, equals,hash,to string, etc. generated by eclipse in Java.
Lot's of time, after I use the auto-generated code-stubs, I add a member variable to the class, and then I need to delete the auto-generated code, and do it all over again.
Is there a way to cause eclipse to add the new variable to the auto-generated code-stubs ?
edit: ok deleting is not essential, however I still have to go and generate each on of them, I'm looking for an automatic solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这并不完全是您问题的解决方案,但我不再使用 Eclipse 自动生成的方法,我使用 Apache 公共语言 EqualsBuilder 和 HashCodeBuilder:
因此,例如您可以这样做:
这使用反射,并且在添加字段时不需要更改。但是,如果您还想考虑超类的 hashCode,还有其他选项可以指定要使用的字段。
编辑:正如已经指出的那样,反射方面可能会带来一些相关的性能损失。就我个人而言,我在生产代码中不使用反射 HashCodeBuilder 或 EqualsBuilder,我使用 toHashCode (如下所示)。不过,我确实使用 ReflectionToStringBuilder 进行日志记录等。
下面是一个不使用反射的示例,但要求您在添加字段时添加另一行:
有关 hashCodeBuilder 的更多讨论,请参阅 apache commons equals/hashcode 生成器
This isn't exactly a solution to your question, but I no longer use the Eclipse auto-generated methods, I use the Apache commons lang EqualsBuilder and HashCodeBuilder:
So, for instance you can do:
This uses reflection, and doesn't need changing when you add a field. However, there are other options where you can specify the fields to use, and if you want to take into account the hashCode of the superclass as well.
EDIT: As has been pointed out, the reflection aspect of this may have some performance penalties associated. Personally, I don't use the reflection HashCodeBuilder or EqualsBuilder in production code, I use the toHashCode (as below). I do however use the ReflectionToStringBuilder for logging and such like.
Here is an example which doesn't use reflection, but requires you to add another line when you add a field:
For more discussion about hashCodeBuilder, see apache commons equals/hashcode builder
查看 www.projectlombok.org 作为您自己编写这些方法的替代方法。特别是 @Data 注释似乎满足您的需求,请参阅 http://www.projectlombok.org/功能/Data.html。
Take a look at www.projectlombok.org as an alternative to writing these methods yourself. In particular the @Data annotation seems to fit your need, see http://www.projectlombok.org/features/Data.html.
我创建了一个自己的项目,其中包含一个字段,并要求 Eclipse 生成所有基本方法。之后我添加了一个新字段,我要求它再次生成这些方法(源 -> 生成...),它提示我替换旧的方法,我单击“是”并显示更新的方法。
希望有帮助
Iv'e created a project of my own with one field and asked eclipse to generate all the base methods. After that I added a new field, I asked it to generate these methods again (source -> generate...), it prompted me about replacing the old ones, I clicked 'yes' and the updated methods were displayed.
Hope it helped