(否)Java 中的属性?

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

(no) Properties in Java?

javagetter-setter

提问by Ishmaeel

So, I have willfully kept myself a Java n00b until recently, and my first real exposure brought about a minor shock: Java does not have C# style properties!

所以,直到最近,我才故意让自己保持 Java n00b,而我第一次真正的接触带来了一个小小的震惊:Java 没有 C# 样式属性!

Ok, I can live with that. However, I can also swear that I have seen property getter/setter code in Java in one codebase, but I cannot remember where. How was that achieved? Is there a language extension for that? Is it related to NetBeans or something?

好吧,我可以忍受。但是,我也可以发誓,我在一个代码库中看到了 Java 中的属性 getter/setter 代码,但我不记得在哪里。这是如何实现的?有语言扩展吗?它与 NetBeans 或其他什么有关吗?

采纳答案by Calum

There is a "standard" pattern for getters and setters in Java, called Bean properties. Basically any method starting with get, taking no arguments and returning a value, is a property getter for a property named as the rest of the method name (with a lowercased start letter). Likewise setcreates a setter of a void method with a single argument.

Java 中有一个用于 getter 和 setter 的“标准”模式,称为Bean properties。基本上任何以 开头get、不带参数并返回值的方法都是一个属性获取器,用于命名为方法名称其余部分的属性(以小写的开头字母)。同样,set创建一个带有单个参数的 void 方法的 setter。

For example:

例如:

// Getter for "awesomeString"
public String getAwesomeString() {
  return awesomeString;
}

// Setter for "awesomeString"
public void setAwesomeString( String awesomeString ) {
  this.awesomeString = awesomeString;
}

Most Java IDEs will generate these methods for you if you ask them (in Eclipse it's as simple as moving the cursor to a field and hitting ctrl-1, then selecting the option from the list).

如果您询问,大多数 Java IDE 将为您生成这些方法(在 Eclipse 中,就像将光标移动到一个字段并按 ctrl-1,然后从列表中选择选项一样简单)。

For what it's worth, for readability you can actually use isand hasin place of getfor boolean-type properties too, as in:

对于它的价值,为了可读性,您实际上可以使用ishas代替get布尔类型的属性,如下所示:

public boolean isAwesome();

public boolean hasAwesomeStuff();

回答by Mark Embling

My Java experience is not that high either, so anyone feel free to correct me. But AFAIK, the general convention is to write two methods like so:

我的 Java 经验也不高,所以任何人都可以随时纠正我。但是AFAIK,一般约定是编写两个方法,如下所示:

public string getMyString() {
    // return it here
}

public void setMyString(string myString) {
    // set it here
}

回答by TK.

If you're using eclipse then it has the capabilities to auto generate the getter and setter method for the internal attributes, it can be a usefull and timesaving tool.

如果您使用的是 eclipse,那么它可以为内部属性自动生成 getter 和 setter 方法,它可以是一个有用且省时的工具。

回答by Hank Gay

The bean convention is to write code like this:

bean 约定是这样编写代码:

private int foo;
public int getFoo() {
    return foo;
}
public void setFoo(int newFoo) {
    foo = newFoo;
}

In some of the other languages on the JVM, e.g., Groovy, you get overridable properties similar to C#, e.g.,

在 JVM 上的其他一些语言中,例如 Groovy,您可以获得类似于 C# 的可覆盖属性,例如,

int foo

which is accessed with a simple .fooand leverages default getFooand setFooimplementations that you can override as necessary.

它可以通过简单的方式访问,.foo并利用您可以根据需要覆盖的默认值getFoosetFoo实现。

回答by Bill Michell

Most IDEs for Java will automatically generate getter and setter code for you if you want them to. There are a number of different conventions, and an IDE like Eclipse will allow you to choose which one you want to use, and even let you define your own.

如果您愿意,大多数 Java IDE 会自动为您生成 getter 和 setter 代码。有许多不同的约定,像 Eclipse 这样的 IDE 将允许您选择要使用的约定,甚至可以让您定义自己的约定。

Eclipse even includes automated refactoring that will allow you to wrap a property up in a getter and setter and it will modify all the code that accesses the property directly, to make it use the getter and/or setter.

Eclipse 甚至包括自动重构,它允许您将属性包装在 getter 和 setter 中,并且它将修改直接访问该属性的所有代码,使其使用 getter 和/或 setter。

Of course, Eclipse can only modify code that it knows about - any external dependencies you have could be broken by such a refactoring.

当然,Eclipse 只能修改它知道的代码 - 您拥有的任何外部依赖项都可能被这种重构破坏。

回答by Cheekysoft

"Java Property Support" was proposed for Java 7, but did not make it into the language.

“Java 属性支持”是针对 Java 7 提出的,但并未将其纳入语言。

See http://tech.puredanger.com/java7#propertyfor more links and info, if interested.

如果有兴趣,请参阅http://tech.puredanger.com/java7#property以获取更多链接和信息。

回答by Scott Stanchfield

I'm just releasing Java 5/6 annotations and an annotation processor to help this.

我只是发布 Java 5/6 注释和注释处理器来帮助解决这个问题。

Check out http://code.google.com/p/javadude/wiki/Annotations

查看http://code.google.com/p/javadude/wiki/Annotations

The documentation is a bit light right now, but the quickref should get the idea across.

现在的文档有点少,但是 quickref 应该能理解这个想法。

Basically it generates a superclass with the getters/setters (and many other code generation options).

基本上它生成一个带有 getter/setter(以及许多其他代码生成选项)的超类。

A sample class might look like

示例类可能看起来像

@Bean(properties = {
    @Property(name="name", bound=true),
    @Property(name="age,type=int.class)
})
public class Person extends PersonGen {
}

There are many more samples available, and there are no runtime dependencies in the generated code.

还有更多示例可用,并且生成的代码中没有运行时依赖项。

Send me an email if you try it out and find it useful! -- Scott

如果您尝试并发现它有用,请给我发电子邮件!——斯科特

回答by dantuch

public class Animal {

    @Getter @Setter private String name;
    @Getter @Setter private String gender;
    @Getter @Setter private String species;
}

This is something like C# properties. It's http://projectlombok.org/

这类似于 C# 属性。这是http://projectlombok.org/

回答by Aleks-Daniel Jakimenko-A.

I am surprised that no one mentioned project lombok

我很惊讶没有人提到lombok 项目

Yes, currently there are no properties in java. There are some other missing features as well.
But luckily we have project lombokthat is trying to improve the situation. It is also getting more and more popular every day.

是的,目前java中没有属性。还有一些其他缺失的功能。
但幸运的是,我们有lombok 项目试图改善这种情况。它也每天越来越受欢迎。

So, if you're using lombok:

因此,如果您使用的是 lombok:

@Getter @Setter int awesomeInteger = 5;

This code is going to generate getAwesomeIntegerand setAwesomeIntegeras well. So it is quite similar to C# auto-implemented properties.

该代码将生成getAwesomeIntegersetAwesomeInteger为好。因此它与C# 自动实现的属性非常相似。

You can get more info about lombok getters and setters here.
You should definitely check out other featuresas well. My favorites are:

您可以在此处获取有关 lombok getter 和 setter 的更多信息。
您也应该检查其他功能。我最喜欢的是:

Lombok is well-integrated with IDEs, so it is going to show generated methods like if they existed (suggestions, class contents, go to declaration and refactoring).
The only problem with lombok is that other programmers might not know about it. You can always delombokthe code but that is rather a workaround than a solution.

Lombok 与 IDE 集成良好,因此它将显示生成的方法,就像它们是否存在一样(建议、类内容、转到声明和重构)。
lombok 的唯一问题是其他程序员可能不知道它。您始终可以对代码进行delombok,但这与其说是解决方案,不如说是一种变通方法。

回答by th1rdey3

From Jeffrey Richter'sbook CLR via C#: (I think these might be the reasons why properties are still not added in JAVA)

来自Jeffrey Richter 的CLR via C#:(我认为这些可能是在 JAVA 中仍未添加属性的原因)

  • A property method may throw an exception; field access never throws an exception.
  • A property cannot be passed as an outor refparameter to a method; a field can.
  • A property method can take a long time to execute; field access always completes immediately. A common reason to use properties is to perform thread synchronization, which can stop the thread forever, and therefore, a property should not be used if thread synchronization is required. In that situation, a method is preferred. Also, if your class can be accessed remotely (for example, your class is derived from System.MarshalByRefObject), calling the property method will be very slow, and therefore, a method is preferred to a property. In my opinion, classes derived from MarshalByRefObjectshould never use properties.
  • If called multiple times in a row, a property method may return a different value each time; a field returns the same value each time. The System.DateTimeclass has a readonly Nowproperty that returns the current date and time. Each time you query this property, it will return a different value. This is a mistake, and Microsoft wishes that they could fix the class by making Now a method instead of a property. Environment's TickCountproperty is another example of this mistake.
  • A property method may cause observable side effects; field access never does. In other words, a user of a type should be able to set various properties defined by a type in any order he or she chooses without noticing any different behavior in the type.
  • A property method may require additional memory or return a reference to something that is not actually part of the object's state, so modifying the returned object has no effect on the original object; querying a field always returns a reference to an object that is guaranteed to be part of the original object's state. Working with a property that returns a copy can be very confusing to developers, and this characteristic is frequently not documented.
  • 属性方法可能会抛出异常;字段访问永远不会抛出异常。
  • 属性不能作为outref参数传递给方法;一个字段可以。
  • 一个属性方法可能需要很长时间才能执行;现场访问总是立即完成。使用属性的一个常见原因是执行线程同步,这可以永远停止线程,因此,如果需要线程同步,则不应使用属性。在这种情况下,首选一种方法。此外,如果您的类可以远程访问(例如,您的类是从 派生的 System.MarshalByRefObject),则调用属性方法会非常慢,因此,方法优先于属性。在我看来,派生自的类不 MarshalByRefObject应该使用属性。
  • 如果连续多次调用,一个属性方法可能每次都返回不同的值;一个字段每次返回相同的值。本System.DateTime类有一个只读 Now返回当前日期和时间属性。每次查询此属性时,它都会返回不同的值。这是一个错误,微软希望他们可以通过使 Now 成为一个方法而不是一个属性来修复这个类。EnvironmentTickCount财产是这个错误的另一个例子。
  • 一个属性方法可能会导致可观察到的副作用;现场访问从来没有。换句话说,一个类型的用户应该能够以他或她选择的任何顺序设置由一个类型定义的各种属性,而不会注意到该类型中的任何不同行为。
  • 一个属性方法可能需要额外的内存,或者返回对实际上不属于对象状态的某些东西的引用,因此修改返回的对象对原始对象没有影响;查询一个字段总是返回一个对象的引用,该对象保证是原始对象状态的一部分。使用返回副本的属性可能会让开发人员感到非常困惑,而且这个特性通常没有记录。