Java 有自动属性吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1698156/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:39:12  来源:igfitidea点击:

Does Java have Automatic Properties?

javalanguage-features

提问by lomaxx

In c# you can setup properties like this:

在 C# 中,您可以设置如下属性:

public int CustomerId {get;set;}

Which sets up an automatic property called CustomerId, but I was wondering if there was anything similar in Java?

它设置了一个名为 CustomerId 的自动属性,但我想知道 Java 中是否有类似的东西?

回答by Jon Skeet

No, Java has nothing similar at the moment. Heck, properties in Java are mostly just conventions of get/set methods, rather than being genuinely understood by the compiler as they are in C#. Tools and libraries recognise the get/set pattern, but the language doesn't know about them. (It's possible that in a future version of Java, there'll be more "formal" support.)

不,Java 目前没有类似的东西。哎呀,Java 中的属性大多只是 get/set 方法的约定,而不是像在 C# 中那样被编译器真正理解。工具和库识别 get/set 模式,但语言不知道它们。(在 Java 的未来版本中,可能会有更多的“正式”支持。)

Some Java-like languages such as Groovydo have automatic property generation, however.

然而,一些类似于 Java 的语言(例如Groovy)确实具有自动属性生成功能。

回答by Joey

No, there isn't such a thing in Java.

不,Java 中没有这样的东西。

In Eclipse, however, you can automatically implement getter/setter methods for fields with Source > Generate Getters/Setters.

但是,在 Eclipse 中,您可以使用 Source > Generate Getters/Setter 自动为字段实现 getter/setter 方法。

回答by David Baakman

Not in the Java language itself. However, there is at least one library that provides that. See: http://projectlombok.org/(or more specific: http://projectlombok.org/features/GetterSetter.html)

不是在 Java 语言本身中。但是,至少有一个库提供了这一点。请参阅:http: //projectlombok.org/(或更具体:http: //projectlombok.org/features/GetterSetter.html

回答by Jorn

You can also do this easily, using the annotations from Project Lombok

您也可以使用Project Lombok 中的注释轻松完成此操作

回答by Stefan

  • The JavaFX properties might also be of interest:
  • JavaFX 属性可能也很有趣:

http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm

http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm

    IntegerProperty num = new SimpleIntegerProperty(666);
    System.out.println(num.getValue());
  • Also see this related question on how to avoid get/set boiler plate code:
  • 另请参阅有关如何避免获取/设置样板代码的相关问题:

"Special attributes/properties" instead of getter/setter in Java to avoid boiler plate code

“特殊属性/属性”而不是 Java 中的 getter/setter 以避免样板代码