(no) Properties in Java?

Viewed 54138

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?

14 Answers

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

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.

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.

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

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,

For me the problem is two fold:

  1. All these extra methods {get*/set*} cluttering up the class code.
  2. NOT being able to treat them like properties:
    public class Test {
      private String _testField;

      public String testProperty {
       get {
        return _testField;
       }
       set {
        _testField = value;
       }
      }
    }

    public class TestUser {
      private Test test;

      public TestUser() {
        test = new Test();

        test.testProperty = "Just something to store";
        System.out.printLn(test.testProperty);
      }
    }

This is the sort of easy assignment I would like to get back to using. NOT having to use 'method' calling syntax. Can anyone provide some answers as to what happened to Java?

I think that the issue is also about the unnecessary clutter in the code, and not the 'difficulty' of creating the setters/getters. I consider them as ugly-code. I like what C# has. I don't understand the resistance to adding that capability to Java.

My current solution is to use 'public' members when protection is not required:

public class IntReturn {
    public int val;
}

public class StringReturn {
    public String val;
}

These would be used to return value from say a Lambda:

StringReturn sRtn = new StringReturn()

if(add(2, 3, sRtn)){
    System.out.println("Value greater than zero");
}

public boolean add(final int a, final int b, final StringReturn sRtn){
    int rtn = a + b;
    sRtn.val = "" + rtn;
    return rtn > 0; // Just something to use the return for.
}

I also really don't like using a method call to set or get an internal value from a class.

If your information is being transferred as 'immutable', then the new Java record could be a solution. However, it still uses the setter/getter methodology, just without the set/get prefixes.

Related