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();
}
Sunday, August 26, 2007
Maven Plugin to generate code using Eclipse JDT
Posted by Shams at 20:33
Labels: Eclipse JDT , Generated Classes , Maven Plugin , Method Injection
Subscribe to:
Post Comments
(
Atom
)
6 comments :
Post a Comment
Thanks!
But I would be glad to help you with pointers if you could be more specific. Basically what I did was as follows:
1) Use JDT to parse my .java file and form a tree
2) Query the tree to find variables defined in that class
3) Process those variable and manipulate tree nodes using JDT to form my new methods
4) Finally write back the new tree to a java file using JDT again
All this was conrolled by my maven plugin which processed all the .java files in my specified directory and wrote back to another specified directory. I used the generate-sources phase for the plugin.
I would be glad to answer if you had further queries
Post a Comment