(no) Properties in Java?

So, until recently, I deliberately kept Java n00b, and my first real exposure caused a little shock: Java has no C # style properties!

Ok, I can live with that. However, I can also swear that I saw getter / setter code in Java on the same code base, but I can’t remember where. How was this achieved? Is there a language extension for this? Is it related to NetBeans or something like that?

+49
java getter-setter
Sep 16 '08 at 8:52
source share
12 answers

There is a standard template for getters and setters in Java called the Bean properties . Basically, any method that starts with get , takes no arguments and returns a value, is a getter attribute for a property called the rest of the method name (with a start letter with a letter). Similarly, set creates the setter of the void method with a single argument.

For example:

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

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

For what it's worth, for readability, you can use is and has instead of get for properties of type boolean, for example:

 public boolean isAwesome(); public boolean hasAwesomeStuff(); 
+59
Sep 16 '08 at 9:00
source share

I am surprised that no one has mentioned the lombok project

Yes, there are currently no properties in java. There are other missing features.
But, fortunately, we are a lombok project that is trying to improve the situation. It is also becoming more popular every day.

So, if you use a lombok:

 @Getter @Setter int awesomeInteger = 5; 

This code will generate getAwesomeInteger and setAwesomeInteger . Thus, it is very similar to C # automatically implemented properties .

You can get more information about lombok getters and setters here .
You should definitely check out other features . My favorites:

Lombok is well integrated with the IDE, so it will show the generated methods, for example, if they exist (sentences, class contents, transition to declaration and refactoring).
The only problem with the Lombok is that other programmers may not be aware of this. You can always delombok code, but this is more a workaround than a solution.

+29
Aug 28 '13 at 19:47
source share
 public class Animal { @Getter @Setter private String name; @Getter @Setter private String gender; @Getter @Setter private String species; } 

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

+6
Aug 28 '13 at 19:45
source share

The bean convention is to write code as follows:

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

In some other JVM languages, like Groovy, you get overridable properties like C #, like

 int foo 

accessed by a simple .foo and using the standard getFoo and setFoo , which you can override as needed.

+5
Sep 16 '08 at 8:59
source share

"Support for Java properties" was proposed for Java 7, but did not fall into this language.

See http://tech.puredanger.com/java7#property for additional links and information if interested.

+5
Sep 16 '08 at 10:20
source share

Most Java IDEs automatically generate getter and setter code for you if you want. There are several different conventions, and an IDE, such as Eclipse, will let you choose which one you want to use, and even let you define your own.

Eclipse even includes automatic refactoring, which will allow you to wrap the property in getter and setter, and it will change all the code that accesses this property directly to use it with getter and / or setter.

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

+3
Sep 16 '08 at 9:03
source share

From Jeffrey Richter’s book CLR via C # : (I think these may be the reasons why properties have not been added to JAVA yet)

  • The property method may throw an exception; field access never throws an exception.
  • A property cannot be passed as an out or ref parameter to a method; field can.
  • The property method can take a lot of time; field access always ends immediately. A common reason for using properties is to perform thread synchronization, which can stop the thread permanently, and therefore, the property should not be used if thread synchronization is required. In this situation, the preferred method. Also, if your class can be retrieved remotely (for example, your System.MarshalByRefObject class), calling the property method will be very slow, and so the method is preferred. In my opinion, classes derived from MarshalByRefObject should never use properties.
  • If you call several times in a row, the property method may return a different value every time; the field returns the same value each time. The System.DateTime class has a read-only Now property that returns the current date and time. Each time you request this property, it will return a different value. This is a mistake, and Microsoft wants them to fix the class by now making a method instead of a property. Environment s The TickCount property is another example of this error.
  • The property method may cause observed side effects; access to the field is never performed. In other words, the type user must be able to set various properties defined by the type in any order that he or she chooses without noticing any other behavior in the type.
  • The property method may require additional memory or return a link to something that is not actually part of the state of the objects, so there is no effect on the original object to change the returned object; a field request always returns a reference to an object that is guaranteed to become part of the state of the original objects. Working with property that returns a copy can be very confusing for developers, and this feature is often not documented.
+3
Dec 26 '13 at 8:56
source share

You may not need the “get” and “set” prefix so that it looks more like properties, you can do this as follows:

 public class Person { private String firstName = ""; private Integer age = 0; public String firstName() { return firstName; } // getter public void firstName(String val) { firstName = val; } // setter public Integer age() { return age; } // getter public void age(Integer val) { age = val; } //setter public static void main(String[] args) { Person p = new Person(); //set p.firstName("Lemuel"); p.age(40); //get System.out.println(String.format("I'm %s, %d yearsold", p.firstName(), p.age()); } } 
+3
Jan 28 '15 at 2:37
source share

My Java experience is not so high, so anyone can fix me. But AFAIK, the general convention, is to write two methods:

 public string getMyString() { // return it here } public void setMyString(string myString) { // set it here } 
+2
Sep 16 '08 at 8:58
source share

If you use eclipse, then it has the ability to automatically generate the getter and setter method for internal attributes, this can be a useful and economical tool.

+1
Sep 16 '08 at 8:59
source share

I am just releasing Java 5/6 annotations and an annotation handler to help with this.

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

The documentation is a little lit right now, but quickref should get this idea.

It basically generates a superclass with getters / setters (and many other code generation options).

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 other samples available, and there is no runtime dependency in the generated code.

Send me a letter if you try it and find it useful! - Scott

+1
Sep 16 '08 at 14:21
source share

And remember: if you code or use classes that only have setters and getters, you are not doing object-oriented development, and you probably shouldn't care about performance. These are called structures and are an integral part of structured procedural programming around the end of the 1980s.

Objects, as a rule, do not have one or very few setters and neither one nor a very small number of getters. Most methods will perform the actual functionality associated with the class in which they are located. To visualize the difference, consider a bean with 10 setters and an object that has a load () method. One encourages encapsulation and therefore will be more understandable and easier to maintain - the other hangs on a street corner and can and is used by anyone, anywhere.

OPTIONAL: for those of you who argue with this because you read somewhere that the presence of functionality in your entities is bad, then I propose this simple solution - to wrap (not copy) an instance of an object in a domain class. This combines code (domain class) with data (entity), so the whole is now a true object. Put all the functionality that works with entity data in the domain class - having done this, no other class should need shared access to the entity, so do not expose these elements and sets, only open the functionality.

-3
Aug 28 '13 at 19:36 on
source share



All Articles