Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JSP/Java how can I replace getter/setter by s.th. more generic?

I am getting tired by adding tons of getters/setters all the time in my beans. Is there a simple way to use annotations to get rid of this stupid work? or any other way? The 2nd example is the short version, which I would like to run, since there is no need to encapsulte my members (though in another context it might be neccessary). In my real world I have to access about 15 classes with about 10 data members in each class which would produce 300 useless setters/getters.

Example TestPerson.java (works):

public class TestPerson {
  public String firstName;
  public String lastName;
  public TestPerson() {
    firstName = "Hugo";
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
}

Example TestPerson.java (does NOT work):

public class TestPerson {
  public String firstName;
  public String lastName;
  public TestPerson() {
    firstName = "Hugo";
  }
}

Example test.jsp

<jsp:useBean id="testperson" class="test.TestPerson" scope="request" />
<html>
<head><title>Test</title></head>
<body>
<h2>Results</h2>${testperson.firstName}<br>
</body>
</html>
like image 378
Alex004 Avatar asked Mar 25 '11 12:03

Alex004


People also ask

How do you avoid getters and setters?

The simplest way to avoid setters is to hand the values to the constructor method when you new up the object. This is also the usual pattern when you want to make an object immutable. That said, things are not always that clear in the real world. It is true that methods should be about behavior.

Can we use getter without setter?

Depends on if the value you are talking about is something you want to let other classes modify - in some cases the answer is yes, in some it is no. If the answer is no then there is no reason to add a setter method and in fact it might harm things.

How do you use setters and getters in two different classes?

To fix this, you need to pass a reference to the GetterAndSetter instance from class A to B . You can do this e.g. by passing it as a parameter to a method of B , or by creating a new instance of A in B and calling a method that provides an instance of GetterAndSetter .


2 Answers

Project Lombok solves this (and much more), and it has support for both Eclipse and Netbeans.

like image 102
gustafc Avatar answered Sep 19 '22 03:09

gustafc


Just have your IDE to autogenerate them. In Eclipse for example, define some properties, rightclick source, choose Source and then Generate Getters and Setters.

enter image description here

like image 22
BalusC Avatar answered Sep 22 '22 03:09

BalusC