does java have something similar to C# properties? [duplicate]

穿精又带淫゛_ 提交于 2019-12-28 01:51:13

问题


C# properties (I mean get and set methods) are a very useful feature. does java have something similar to C# properties too. I mean how we can implement something like the following C# code in java:

public string Name
{
    get
    {
        return name;
    }

    set
    {
        name = value;
    }
}

thank you in advance


回答1:


No, Java does not have the equivalence. It only has accessor and mutator methods, fancy names for getter and setter methods. For example:

public class User {
    private String name;

    public String getName() { return this.name; }
    public void setName(String name) { this.name = name; }
}



回答2:


You could have a look at Project Lombok as it tries to take the pain out of writing boiler plate Java code. It allows you to either use @Getter and @Setter annotations, which will provide getBlah() and setBlah() methods:

public class GetterSetterExample {
  @Getter @Setter private int age = 10;
}

Or you can just use @Data and it will automatically implement your hashCode(), equals(), toString() and getter methods, along with setters on non-final fields:

@Data public class DataExample {
  private String name;
}

Problems I have found with the project, however, are that it's all a bit voodoo, which can be off-putting, and that you have to install an Eclipse (or what ever) plugin to get auto compilation to work.




回答3:


Properties are not only convenient in terms of writing getters and setters encapsulated in a unit , but also they provide a good syntax at the point of call.

Window.Title =  "New"; //which looks natural

while with getters and setters it is usually

Window.setTitle("New");



回答4:


There has been a proposal to add C#-like support for properties (and events) to Java, but it looks like this is rejected for the next version of Java (Java 7).

See:

  • Why will there be no native properties in Java 7?
  • Java Properties Without Getters and Setters



回答5:


You can just declare a private variable, and write the methods by hand. However, if you are using Eclipse, you can click on a variable, select "Source" and "Generate getters and setters." This is about as convenient as C# properties.



来源:https://stackoverflow.com/questions/2963243/does-java-have-something-similar-to-c-sharp-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!