Saturday, July 18, 2009

Groovy Simple Pojo Step 3

Groovy makes writing Java code a lot simpler. For example, lets create a simple pojo.


Create a Java class called Person and copy the following code into that class.

package com.groovy.home;

public class Person {

private String firstName;
private String lastName;
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;
}
public String toString()
{
return firstName+" "+lastName;
}
}

Paste the following code into your main class in your HelloWorld.groovy class and compile it.

Person p=new Person();
p.setFirstName("Bob");
p.setLastName("Jones");
System.out.println("My Name is: "+p);

This code will create a simple POJO class and print the name of the Person to your console. However, groovy can make this code a whole lot simpler. Copy the code from your Person.java class, delete the Person.java class, create a Person.groovy class and paste the code into that class. When you run your HelloWorld.groovy class, the same information is printed out. Using groovy, you can simplify the Person.groovy class to make it a lot simplier.

Replace the Person.groovy code with this code and you can notice how many lines of code you have just eliminated.

package com.groovy.home

public class Person{

String firstName
String lastName
public String toString()
{
return firstName+" "+lastName;
}
}

All methods for POGOs are public by default and all attributes are private. Each field automatically comes with setters and getters. These methods are auto generated in the byte code and not the source code.

In my next post I will discuss some other Java shortcuts using Groovy.



Go To Step 4

0 comments: