Sunday, August 26, 2007

Maven Plugin to generate code using Eclipse JDT

Recently we were facing troubles with the generated sources for our project. The problem was that the java sources generated for our web service client using cxf did not have a proper toString() or equals() method both of which we needed.

We were using maven for building our project and manage dependencies. The idea struck me why not have a maven plugin to modify the generated sources. So we decided on creating a maven plugin to do just that. I had previous experience with eclipse and knew it had something called JDT to form a syntax tree from java source text. In addition, maven build life cycle has a process-sources phase just after the generate-sources phase which was just perfect for us.

Now we have to plugin which generates the toString(), equals() and hashCode() methods and relieved us a lot of debugging effort.

Below is sample code generated using the plugin on a class:

@Override public boolean equals( final Object pOtherObject){
if (pOtherObject == null) {
return false;
}
if
(this.getClass().equals(pOtherObject.getClass())) {
return id ==
((Event)pOtherObject).id;
}
return super.equals(pOtherObject);
}

@Override public int hashCode(){
return this.getId();
}

@Override public String toString(){
StringBuilder eStringBuilder;
eStringBuilder=new StringBuilder();
eStringBuilder.append("Class");
eStringBuilder.append(" : ");
eStringBuilder.append(getClass());
eStringBuilder.append(" , ");
eStringBuilder.append("Id");
eStringBuilder.append(" : ");
eStringBuilder.append(id);
eStringBuilder.append(" , ");
eStringBuilder.append("Artists");
eStringBuilder.append(" : ");
if (artists != null) {
eStringBuilder.append(" [ ");
for ( Artist eArtist : artists) {
if
(eArtist != null) {
eStringBuilder.append(eArtist);
} else {
eStringBuilder.append("null");
}
eStringBuilder.append(" , ");
}
eStringBuilder.append(" ] ");
} else {
eStringBuilder.append("null");
}
eStringBuilder.append(" , ");
eStringBuilder.append("Name");
eStringBuilder.append(" : ");
eStringBuilder.append(name);
eStringBuilder.append(" , ");
return
eStringBuilder.toString();
}


--

6 comments :