In JSP / Java, how can I replace getter / setter with s.th. more general?

I get tired by adding tons of getters / setters all the time in my beans. Is there an easy way to use annotations to get rid of this stupid job? or any other way? The second example is a short version that I would like to run, since there is no need to encapsulate my members (although in a different context this may be necessary). In my real world, I need to access 15 classes with about 10 data members in each class, which will create 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 (NOT working):

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

Test.jsp example

 <jsp:useBean id="testperson" class="test.TestPerson" scope="request" /> <html> <head><title>Test</title></head> <body> <h2>Results</h2>${testperson.firstName}<br> </body> </html> 
+7
source share
5 answers

The Lombok project solves this problem (and much more), and it supports both Eclipse and Netbeans .

+9
source

Just create an IDE to auto-generate them. For example, in Eclipse, define some properties, right-click source, select Source, and then Generate Recipients and Setters.

enter image description here

+9
source

Do you find using Groovy's scripting language? It is based on Java and generates Java Bytecode.

See this link: http://groovy.codehaus.org/Groovy+Beans getters and setters are implicit.

+2
source

There is also a scala:

 class foo { @BeanProperty var s1 : String, @BeanProperty var i1 : int } 

You can use the scala compiler to generate java byte code that this class would create, as well as the corresponding private fields, getter and setter methods.

However, if you want to stick with plain java, I doubt java will soon see support for first class properties. Your best bet is some code generation. You could generate them using annotations and annotation processors, although this could lead to an eclipse application. EDIT: This is what Lombok (as mentioned above) seems to be doing. It generates the source code for you during compilation based on annotations.

0
source

Try write-it-once . Template-based code generator. You write a custom template with Groovy and create a file based on java reflections. This is the easiest way to create any file. You can create getters / settest / toString by creating AspectJ or java files, SQL based on JPA annotations, insert / update based on enumerations, etc.

0
source

All Articles