Java 约定中的 Getter 和 Setter
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18046071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getters and Setters in Java convention
提问by Dimitar Dimitrov
My Java is a bit rusty (been doing C# for the last couple of years). Also I hope this won't be a very subjective question.
我的 Java 有点生疏(过去几年一直在做 C#)。我也希望这不会是一个非常主观的问题。
Anyway say I had class Person
(yeah a bit of a cliche, I know), with no behaviour (C# version):
无论如何说我有课Person
(是的,有点陈词滥调,我知道),没有行为(C# 版本):
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
// say 10+ properties
}
How would the equivalent Java version look like ? I know I can write bunch of getters and setters (but say I had 10+ properties), it feels like a lot of boilerplate. Is it considered bad practice to just do:
等效的 Java 版本会是什么样子?我知道我可以编写一堆 getter 和 setter(但假设我有 10 多个属性),感觉就像很多样板。这样做是否被认为是不好的做法:
public class Person {
public String name;
public int age;
// rest of the stuff here
}
I feel a bit uneasy about this. I realise there is no "right answer" but, I'm more interested in the general conventions and best practices.
我对此感到有些不安。我意识到没有“正确答案”,但是,我对一般约定和最佳实践更感兴趣。
采纳答案by Petar Minchev
You should write getters and setters. Or better - let your IDE generate them automatically. Otherwise you break the encapsulation. Also maybe you need just a getter.
您应该编写 getter 和 setter。或者更好 - 让您的 IDE 自动生成它们。否则你会破坏封装。也许你只需要一个吸气剂。
Another advantage of using a getter or setter can be doing some checks or preprocessing before returning or setting the field.
使用 getter 或 setter 的另一个优点是在返回或设置字段之前进行一些检查或预处理。
Here is a sample code snippet:
这是一个示例代码片段:
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
Optionally you can use http://projectlombok.org/and write it like this using annotations:
您可以选择使用http://projectlombok.org/并使用注释像这样编写:
@Getter @Setter
private String name;
The code generation is done compile time.
代码生成在编译时完成。
回答by Vaughan Hilts
You have to create manual functions to do it.
您必须创建手动功能才能做到这一点。
So first, you create a backing field.
因此,首先,您创建一个支持字段。
private String _backingString
Then you create getters and mutators
然后你创建 getter 和 mutator
public String getBackingString()
{
return this._backingString;
}
public String setBackingString(String value)
{
this._backingString = value;
}
It's the Java convention - there's no other way around it. However, you'll be pleased to know most IDEs have tools to generate these. Just google around for your favourite IDEs generator tool.
这是 Java 约定——别无他法。但是,您会很高兴知道大多数 IDE 都有生成这些的工具。只需谷歌搜索您最喜欢的 IDE 生成器工具。
回答by Micha? Tabor
You should do getters and setters for each. Modern IDE's make it easy because they have auto-insert option. Eventually you can create get and set methods in Calendar's class style.
你应该为每个人做 getter 和 setter。现代 IDE 使其变得容易,因为它们具有自动插入选项。最终,您可以在 Calendar 的类样式中创建 get 和 set 方法。
回答by Dan94
Which IDE are you using? In Eclipse you can create them automatically from the source menu, and their names are derived from the field names. Code:
您使用的是哪个 IDE?在 Eclipse 中,您可以从源菜单中自动创建它们,它们的名称来自字段名称。代码:
private String myField;
public String getMyField()
{
return this.myField;
}
public void setMyField(String value)
{
//validation stuff
this.myField = value;
}
回答by lreeder
It's better to have getter/setters to return the fields so that you can encapsulate the way the fields are calculated. Although it happens rarely, there may come a time when you want to change something like this:
最好让 getter/setter 返回字段,以便您可以封装字段的计算方式。尽管这种情况很少发生,但有时您可能会想要更改以下内容:
getBalance()
{
return this.staticBalance;
}
to this:
对此:
getBalance()
{
return calculateBalance();
}
And the only way in Java to change field behavior without potentially changing tons of code (or worse requiring your API users to change bunches of code) is to use getters and setters.
在 Java 中改变字段行为而不可能改变大量代码(或更糟糕的是要求你的 API 用户改变大量代码)的唯一方法是使用 getter 和 setter。
Other benefits are:
其他好处是:
- Ability for subclasses to override the behavior
- Improved thread safety because you can synchronize access
- 子类覆盖行为的能力
- 提高了线程安全性,因为您可以同步访问
Writing the boilerplate is tedious, but a good IDE will just generate those methods for you from the field names.
编写样板文件很乏味,但好的 IDE 只会根据字段名称为您生成这些方法。
回答by denov
I often use both approaches, having getters and setters and not. I always use private fields which force the use of getters and setters in my model. Using JPA and Hibernate my model is tied to my DB schema. Then for my DTOs which are normally used for things like RESTful services I use mostly public fields with no getters and setters. These DTOs have no logic and get marshaled out to JSON or created from JSON that's being set from a client so I find no need for the getters and setters. I usually don't end up override equals and hashCode for these too. They are as simple as possible.
我经常使用这两种方法,有 getter 和 setter,但没有。我总是使用私有字段,这会强制在我的模型中使用 getter 和 setter。使用 JPA 和 Hibernate,我的模型与我的数据库模式相关联。然后,对于通常用于 RESTful 服务之类的 DTO,我主要使用没有 getter 和 setter 的公共字段。这些 DTO 没有逻辑,被编组为 JSON 或从客户端设置的 JSON 创建,所以我发现不需要 getter 和 setter。我通常也不会为这些覆盖 equals 和 hashCode。它们尽可能简单。
So I don't think there's a right or wrong way and it depends on usage.
所以我认为没有正确或错误的方式,这取决于用法。
And if you are going to create you getters and setters let your IDE do the work for you.
如果您要创建 getter 和 setter,让您的 IDE 为您完成工作。