Question

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!

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?

Was it helpful?

Solution

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 set creates a setter of a 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 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).

For what it's worth, for readability you can actually use is and has in place of get for boolean-type properties too, as in:

public boolean isAwesome();

public boolean hasAwesomeStuff();

OTHER TIPS

I am surprised that no one mentioned project lombok

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

So, if you're using lombok:

@Getter @Setter int awesomeInteger = 5;

This code is going to generate getAwesomeInteger and setAwesomeInteger as well. So it is quite similar to C# auto-implemented properties.

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

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 delombok the code but that is rather a workaround than a solution.

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

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

The bean convention is to write code like this:

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

int foo

which is accessed with a simple .foo and leverages default getFoo and setFoo implementations that you can override as necessary.

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/

You may not need for "get" and "set" prefixes, to make it look more like properties, you may do it like this:

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());
    }
}

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.

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.

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

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

  • A 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; 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 MarshalByRefObject should 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.DateTime class has a readonly Now property 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 TickCount property 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.

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:

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

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

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.

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

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

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

Basically it generates a superclass with the 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 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

There is no property keyword in java (like you could find it in C#) the nearest way to have 1 word getter/setter is to do like in C++:

public class MyClass
{
    private int aMyAttribute;
    public MyClass()
    {
        this.aMyAttribute = 0;
    }
    public void mMyAttribute(int pMyAttributeParameter)
    {
        this.aMyAttribute = pMyAttributeParameter;
    }
    public int mMyAttribute()
    {
        return this.aMyAttribute;
    }
}
//usage :
int vIndex = 1;
MyClass vClass = new MyClass();
vClass.mMyAttribute(vIndex);
vIndex = 0;
vIndex = vClass.mMyAttribute();
// vIndex == 1

As previously mentioned for eclipse, integrated development environment (IDE) often can create accessor methods automatically.

You can also do it using NetBeans.

To create accessor methods for your class, open a class file, then Right-click anywhere in the source code editor and choose the menu command Refactor, Encapsulate Fields. A dialog opens. Click Select All, then click Refactor. Voilà,

Good luck,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top