Java Getter 和 Setter

发布于 2024-08-15 02:38:41 字数 147 浏览 7 评论 0原文

在 Java 中是否有更好的标准方法来创建 getter 和 setter?

必须为每个变量显式定义 getter 和 setter,这是相当冗长的。有没有更好的标准注释方法?

Spring有这样的东西吗?

即使 C# 也有属性。

Is there a better standard way to create getters and setters in Java?

It is quite verbose to have to explicitly define getters and setters for each variable. Is there a better standard annotations approach?

Does Spring have something like this?

Even C# has properties.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

滥情空心 2024-08-22 02:38:41

我不确定您是否认为它是“标准”,但是 Project Lombok 解决这个问题。他们使用注释来取代 Java 的大部分冗长内容。

有些人正在寻找替代的 Java 兄弟语言,例如 Groovy 或 Scala。我担心 JSR 要想找到一种“标准化”方法来“修复”Java 中的这个问题,可能需要几年的时间(如果有的话)。

I'm not sure if you'd consider it 'standard', but Project Lombok addresses this problem. They use annotations to replace much of the verbosity of Java.

Some people are looking at alternative Java sibling languages, such as Groovy or 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.

哆兒滾 2024-08-22 02:38:41

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

Eclipse has a context menu option that will auto-generate these for you, as I am sure many other IDE's do.

南街女流氓 2024-08-22 02:38:41

我创建了一些不特定于 Eclipse 的注释。

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

例如:

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 {
}

我的注解生成一个超类;我认为 Lombok 修改了正在编译的实际类(Sun 官方不支持该类,并且可能会中断 - 我可能对它的工作方式是错误的,但根据我所看到的,他们一定是这样做的)

享受吧!
——斯科特

I've created some annotations that are not eclipse-specific.

See 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)

Enjoy!
-- Scott

番薯 2024-08-22 02:38:41

尝试这样的事情:

@Getter @Setter private int Age = 10;

更多信息如下:

https://projectlombok.org/features/GetterSetter

Try something like this:

@Getter @Setter private int age = 10;

More info below:

https://projectlombok.org/features/GetterSetter

忆依然 2024-08-22 02:38:41

这是关于该主题的有趣文章:
http://cafe.elharo .com/java/why-java-doesnt-need-properties-it-already-has-them/

我认为属性是一个快捷方式,但它更多的是一个小功能而不是真正的重要功能

Here is an interesting articles about the subject:
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

陈独秀 2024-08-22 02:38:41

大多数 IDE 都提供了生成代码的快捷方式(例如Eclipse:右键单击 -> 源代码 -> 生成 Getters 和 Setters),尽管我意识到这可能不是您正在寻找的答案。

一些 IOC 框架允许您注释属性,以便它们可以在框架的上下文中使用,例如 Tapestry IOC 和最新的 Spring,我认为(但这种用途仅限于框架使用)

Most IDEs provide a shortcut for generating the code (e.g. Eclipse: Right click -> Source -> Generate Getters & Setters), although I realise this is probably not the answer you are looking for.

Some IOC frameworks allow you to annotate properties so that they can be used in the context of the framework e.g. Tapestry IOC, and the latest Spring, I think (but this use is limted to use by the framework)

莳間冲淡了誓言ζ 2024-08-22 02:38:41

作为可能的替代方案,您尝试过 Scala 吗?它编译为 Java 字节码,并有许多有趣的快捷方式,可以让您作为 Java 程序员的生活更轻松。

属性例如:

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

和输出:

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

As a possible alternative, have you tried Scala? It compiles to Java bytecode, and has lots of interesting shortcuts which can make your life as a Java programmer easier.

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
乖乖公主 2024-08-22 02:38:41

我同意 getter/setter 很冗长。 龙目岛项目
正如其他人所建议的那样,有很好的答案。
否则,您可以使用 IDE 的功能来生成它们。

I agree that getter/setters are verbose. Project Lombok
has good answer for it as suggested by others.
Otherwise, you could use your IDE's capability to generate them.

清醇 2024-08-22 02:38:41

还有 Spring Roo 项目及其 @RooJavaBean 注释。它还具有 @RooToString 和 @RooHashCodeEquals 或类似的东西。它使用适当的方法在后台生成 AspectJ 文件。

There is also Spring Roo project with its @RooJavaBean annotation. It has also @RooToString and @RooHashCodeEquals or something like that. It generates in background an AspectJ file with proper methods.

余罪 2024-08-22 02:38:41

使用 Netbeans,只需在要替换 getter/setter 的位置开始输入 get 或 set 并调用自动完成(Ctrl+Space),它就会为您提供生成 getter 或 setter 的选项。它还将为您提供生成构造函数的选项。

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. It'll also give you an option to generate a constructor as well.

勿忘初心 2024-08-22 02:38:41

没有比“属性”关键字更好的方式将其作为语言的一部分了。

正如其他人提到的,一种替代方法是使用 IDE 生成它们。另外,如果您有很多需要此功能的对象,则可以编写自己的代码生成工具,该工具采用基类并生成带有 getter 和 setter 的包装器。

您还可以简单地将变量公开为公共成员。然而,当您决定添加验证逻辑时,这可能会再次伤害您。

然而,最后一个想法是:除非您的类只是用于传输数据,否则它们可能不应该公开其内部状态。 IMO,带有 getter 和 setter 的“行为”类是一种代码味道。

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. 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.

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.

夏夜暖风 2024-08-22 02:38:41

如果您需要只读类,请查看 Java Records。它自动生成 getter 和方法,例如 equals 和 hashcode。但是,此功能尚未稳定,目前您可以将其用作实验性功能(可能会在 Java 16 上稳定)。
https://dzone.com/articles/introducing-java-record

In the case that you need a read-only class, take a look at Java Records. It auto-generates getters and methods like equals and hashcode. However, this feature is not stabilized and currently you can use it as an experimental feature (Probably will be stabilized on Java 16).
https://dzone.com/articles/introducing-java-record

樱&纷飞 2024-08-22 02:38:41

是的,你有点不走运。 Groovy 确实会为您生成它们,但标准 java 中没有骰子。如果您使用 Eclipse,您可以 很容易生成它们,以及生成 hashCode() 和 equals() 函数。

Yeah, you are kind of out of luck. Groovy does generate them for you, but no dice in standard java. If you use Eclipse you can generate them pretty easily, as well as generate hashCode() and equals() functions.

感情废物 2024-08-22 02:38:41

这就是 IDE 的工作,生成重复的冗长代码作为 getters/setters

That's the work of the IDE to generate repetitive verbose code as getters/setters

零時差 2024-08-22 02:38:41

使用您的 IDE 为您生成它,并尝试最大程度地减少您拥有的 getter/setter 的数量 - 您可能会享受到不变性的额外好处。

我喜欢 C# 的属性语法,我认为它非常漂亮、干净,非常干净。

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.

I like the C# syntax for properties, I think it's pretty and clean, and pretty clean.

旧人 2024-08-22 02:38:41

好吧,一种选择是不要那么害怕公共场所。对于您知道永远不会在获取和设置方面进行验证或额外工作的简单类,公共字段需要更少的样板文件,语法上更好,并且更高效。

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.

巷雨优美回忆 2024-08-22 02:38:41

如果您使用 emacs,则可以定义一个 emacs 宏来为您执行此操作。有 emacs 高手吗? :)

If you use emacs it might be possible to define an emacs macro that does this for you. Any emacs gurus out there? :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文