Alex Rivera | Logout

What is the Java Equivalent of Python's property()?

Asked 2010-01-13T13:03:49.087
11

I'm new to Java, and I'd like to create some class variables that are dynamically calculated when accessed, as you can do in Python by using the property() method. However, I'm not really sure how to describe this, so Googling shows me lots about the Java "Property" class, but this doesn't appear to be the same thing. What is the Java equivalent of Python's property()?

Edit
Report

1 Answer

10

There's no such facility built into Java language. You have to write all the getters and setters explicitly by yourself. IDEs like Eclipse can generate this boilerplate code for you though.

For example :

class Point{
  private int x, y;

  public Point(int x, int y){
    this.x = x;
    this.y = y;
  }

  public void setX(int x){
    this.x = x;
  }

  public int getX(){
    return x;
  }

  public void setY(int y){
    this.y = y;
  }

  public int getY(){
    return y;
  }
}

You might want to have a look at Project Lombok which provides the annotations @Getter and @Setter that are somewhat similar to Python's property.

With Lombok, the above example reduces to :

class Point{
  @Getter @Setter private int x, y;

  public Point(int x, int y){
    this.x = x;
    this.y = y;
  }
}
answered 2010-01-13T13:08:30.137

Your Answer