简体   繁体   English

Java Getter 和 Setter

[英]Java Getters and Setters

Is there a better standard way to create getters and setters in Java?有没有更好的标准方法来在 Java 中创建 getter 和 setter?

It is quite verbose to have to explicitly define getters and setters for each variable.必须为每个变量显式定义 getter 和 setter 是非常冗长的。 Is there a better standard annotations approach?有没有更好的标准注释方法?

Does Spring have something like this? Spring有这样的东西吗?

Even C# has properties.甚至 C# 也有属性。

I'm not sure if you'd consider it 'standard', but Project Lombok addresses this problem.我不确定您是否认为它是“标准的”,但Project Lombok解决了这个问题。 They use annotations to replace much of the verbosity of Java.他们使用注释来代替 Java 的大部分冗长。

Some people are looking at alternative Java sibling languages, such as Groovy or Scala.有些人正在寻找替代的 Java 兄弟语言,例如 Groovy 或 Scala。 I'm afraid it will take some years -if at all- before the JSR figures out a "standardized" way to "fix" this in Java proper.恐怕要花几年的时间——如果有的话——JSR 才能找到一种“标准化”的方法来在 Java 中适当地“修复”这个问题。

Eclipse 有一个上下文菜单选项,可以为您自动生成这些选项,我相信许多其他 IDE 都会这样做。

I've created some annotations that are not eclipse-specific.我创建了一些不是特定于 eclipse 的注释。

See http://code.google.com/p/javadude/wiki/Annotations请参阅http://code.google.com/p/javadude/wiki/Annotations

For example:例如:

package sample;

import com.javadude.annotation.Bean;
import com.javadude.annotation.Property;
import com.javadude.annotation.PropertyKind;

@Bean(properties={
    @Property(name="name"),
    @Property(name="phone", bound=true),
    @Property(name="friend", type=Person.class, kind=PropertyKind.LIST)
}) 
public class Person extends PersonGen {
}

My annotations generate a superclass;我的注释生成了一个超类; I think Lombok modifies the actual class being compiled (which is officially not supported by Sun and may break - I could be wrong about how it works, but based on what I've seen they must be doing that)我认为 Lombok 修改了正在编译的实际类(Sun 正式不支持它并且可能会中断 - 我可能对它的工作方式有误,但根据我所看到的,他们必须这样做)

Enjoy!享受! -- Scott ——斯科特

Most IDEs provide a shortcut for generating the code (eg Eclipse: Right click -> Source -> Generate Getters & Setters ), although I realise this is probably not the answer you are looking for.大多数 IDE 都提供了生成代码的快捷方式(例如Eclipse:右键单击 -> 源 -> 生成 Getters & Setters ),尽管我意识到这可能不是您正在寻找的答案。

Some IOC frameworks allow you to annotate properties so that they can be used in the context of the framework eg Tapestry IOC, and the latest Spring, I think (but this use is limted to use by the framework)一些 IOC 框架允许您注释属性,以便它们可以在框架的上下文中使用,例如 Tapestry IOC 和最新的 Spring,我认为(但这种用法仅限于框架使用)

Here is an interesting articles about the subject: http://cafe.elharo.com/java/why-java-doesnt-need-properties-it-already-has-them/这是关于该主题的有趣文章: http : //cafe.elharo.com/java/why-java-doesnt-need-properties-it-already-has-them/

I think properties are a shortcut but it's more a little feature than a real important feature我认为属性是一个捷径,但它更多的是一个小功能而不是一个真正重要的功能

I agree that getter/setters are verbose.我同意 getter/setter 是冗长的。 Project Lombok has good answer for it as suggested by others.正如其他人所建议的那样,龙目岛项目对此有很好的答案。 Otherwise, you could use your IDE's capability to generate them.否则,您可以使用 IDE 的功能来生成它们。

There is also Spring Roo project with its @RooJavaBean annotation.还有带有 @RooJavaBean 注释的 Spring Roo 项目。 It has also @RooToString and @RooHashCodeEquals or something like that.它还有@RooToString 和@RooHashCodeEquals 或类似的东西。 It generates in background an AspectJ file with proper methods.它在后台使用适当的方法生成 AspectJ 文件。

With Netbeans, just start typing get or set where the getter/setter is to be replaced and call up auto complete (Ctrl+Space), it'll give you the option to generate the getter or setter.使用 Netbeans,只需在要替换 getter/setter 的位置开始键入 get 或 set 并调用自动完成 (Ctrl+Space),它就会为您提供生成 getter 或 setter 的选项。 It'll also give you an option to generate a constructor as well.它还会为您提供生成构造函数的选项。

There is no better way that's part of the language -- nothing like a "property" keyword.没有更好的方法是语言的一部分 - 没有什么像“属性”关键字那样。

One alternative, as other people have mentioned, is to use your IDE to generate them.正如其他人所提到的,另一种选择是使用您的 IDE 来生成它们。 Another, if you have a lot of objects that need this, is to write your own code generation tool that takes a base class and produces a wrapper with getters and setters.另一个,如果你有很多需要这个的对象,是编写你自己的代码生成工具,它接受一个基类并生成一个带有 getter 和 setter 的包装器。

You could also simply expose the variables as public members.您也可以简单地将变量公开为公共成员。 However, down the road this will probably come back to hurt you, when you decide to add validation logic.然而,当您决定添加验证逻辑时,这可能会再次伤害您。

However, one final thought: unless your classes are used simply to transfer data, they probably shouldn't expose their internal state.但是,最后一个想法:除非您的类仅用于传输数据,否则它们可能不应该公开其内部状态。 IMO, "behavior" classes with getters and setters are a code smell. IMO,带有 getter 和 setter 的“行为”类是一种代码气味。

As a possible alternative, have you tried Scala ?作为可能的替代方案,您是否尝试过Scala It compiles to Java bytecode, and has lots of interesting shortcuts which can make your life as a Java programmer easier.它编译为 Java 字节码,并有许多有趣的快捷方式,可以让您作为 Java 程序员的生活更轻松。

Properties for instance:属性例如:

case class Person(var name:String, 
                  var age:Int);
val p = Person("John", 4)
p.name
p.name = "Charlie"
p.name

And the output:和输出:

defined class Person
p: Person = Person(John,4)
res7: String = John
res8: String = Charlie

Try something like this:尝试这样的事情:

@Getter @Setter private int age = 10; @Getter @Setter 私有整数年龄 = 10;

More info below:更多信息如下:

https://projectlombok.org/features/GetterSetter https://projectlombok.org/features/GetterSetter

Yeah, you are kind of out of luck.是的,你有点不走运。 Groovy does generate them for you, but no dice in standard java. Groovy 确实为您生成它们,但在标准 java 中没有骰子。 If you use Eclipse you can generate them pretty easily , as well as generate hashCode() and equals() functions.如果您使用 Eclipse,您可以非常轻松地生成它们,以及生成 hashCode() 和 equals() 函数。

In the case that you need a read-only class, take a look at Java Records.如果您需要只读类,请查看 Java Records。 It auto-generates getters and methods like equals and hashcode.它自动生成 getter 和方法,如 equals 和 hashcode。 However, this feature is not stabilized and currently you can use it as an experimental feature (Probably will be stabilized on Java 16).但是,此功能尚未稳定,目前您可以将其用作实验性功能(可能会在 Java 16 上稳定)。 https://dzone.com/articles/introducing-java-record https://dzone.com/articles/introducing-java-record

这是 IDE 生成重复冗长代码作为 getter/setter 的工作

Use your IDE to generate it for you and try to minimize the amount of getters/ setters that you have - you will likely enjoy the added benefit of immutability.使用您的 IDE 为您生成它并尽量减少您拥有的 getter/setter 的数量 - 您可能会享受不变性的额外好处。

I like the C# syntax for properties, I think it's pretty and clean, and pretty clean.我喜欢属性的 C# 语法,我认为它非常干净,而且非常干净。

Well, one option is don't be so afraid of public fields.好吧,一种选择是不要那么害怕公共领域。 For simple classes that you know will never do validation or extra work under the hood on get and set, public fields require less boilerplate, are syntactically nicer, and are more efficient.对于您知道永远不会在 get 和 set 上进行验证或额外工作的简单类,公共字段需要更少的样板,在语法上更好,并且更有效。

If you use emacs it might be possible to define an emacs macro that does this for you.如果您使用 emacs,则可以定义一个为您执行此操作的 emacs 宏。 Any emacs gurus out there?有 emacs 大师吗? :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM