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>
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.
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.
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 .
Project Lombok solves this (and much more), and it has support for both Eclipse and Netbeans.
Just have your IDE to autogenerate them. In Eclipse for example, define some properties, rightclick source, choose Source and then Generate Getters and Setters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With