Carl-Petter Bertell is a Software Creative who dabbles in the art of Java. Carl-petter has posted 1 posts at DZone. View Full User Profile

Using Java 6 Processors in Eclipse

02.07.2011
| 17720 views |
  • submit to reddit

JDK5 introduced the APT (Annotation Processing Tool). It was part of the SDK but the classes were part of the unofficial com.sun.* namespace, and you had to use the apt tool to process the source code.

JDK6 cleaned up the API and integrated this stuff it into javac itself so you didn’t need to use the separate apt tool anymore.

Apparently built for processing source code with annotations before they are compiled into classes, it can also be used for all kinds of fun like code generation and code analyzers which are IDE independent; and you don’t even need to use annotations necessarily. The JPA2 criteria api meta-model is generated using this.

I made one very contrived example of java6 processor usage with Eclipse. All of this is possible to integrate into a maven build but I’m leaving that out and focusing on how I got this processing to work within Eclipse.

So we’re creating a processor which will generate a new class for each class in projects compiled using this processor. Additionally we’ll create a Warning for each class which starts with a T. Yes it’s silly.

Step 1: Create the processor project

SillyProcessor.java:

@SupportedAnnotationTypes(value= {"*"})
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class SillyProcessor extends AbstractProcessor { 

	private Filer filer;
	private Messager messager;

	@Override
	public void init(ProcessingEnvironment env) {
		filer = env.getFiler();
		messager = env.getMessager();
	}

	@Override
	public boolean process(Set elements, RoundEnvironment env) {

		for (Element element : env.getRootElements()) {

			if (element.getSimpleName().toString().startsWith("Silly")) {
				// We don't want generate new silly classes
				// for auto-generated silly classes
				continue;
			}

			if (element.getSimpleName().toString().startsWith("T")) {
				messager.printMessage(Kind.WARNING,
					"This class name starts with a T!",
					element);
			}

			String sillyClassName = "Silly" + element.getSimpleName();
			String sillyClassContent =
					"package silly;\n"
				+	"public class " + sillyClassName + " {\n"
				+	"	public String foobar;\n"
				+	"}";

			JavaFileObject file = null;

			try {
				file = filer.createSourceFile(
						"silly/" + sillyClassName,
						element);
				file.openWriter()
					.append(sillyClassContent)
					.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		return true;
	}
}

Without creating this META-INF entry I couldn’t get the processor to register in Eclipse.

META-INF/services/javax.annotation.processing.Processor:

com.kerebus.annotation.processor.SillyProcessor

Its only contents is the name of the Processor implementation. I guess you might be able to list several processors here, although I’m not sure.

That’s it. Now export it as a jar and use that jar in other projects where you wish to use the processor.

STEP 2: Create a project which uses your processor.

In the properties for your new project go to Java Compiler -> Annotation Processing
Check the “Enable Project Specific Settings” and make sure “Enable annotation processing” is checked. I also changed the generated source directory to a name which didn’t start with a dot so it wouldn’t be hidden in the package explorer (files or directories which start with a dot are by default filtered away in eclipse).

Next off go to Java Compiler -> Annotation Processing -> Factory Path
Here you should add the jar of your processor project. You cannot use project references.
Press the “Advanced” button and you’ll be presented with a dialog which contains the processor you defined in your META-INF/services/javax.annotation.processing.Processor file. Select it and press ok.

Step 3: Build!

We’re practically done. Here’s what it looks like for me in my project:

So we get a warning for the Thing class because its class name start with a “T” and for each class in the project we get corresponding “Silly” classes generated. These are compiled and usable just like any other normal class.

For more info check out the eclipse jdt/apt docs, this bit about creating a code analyzer or the offical docs

From http://kerebus.com/2011/02/using-java-6-processors-in-eclipse/.

Published at DZone with permission of its author, Carl-petter Bertell.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Mohamed El-beltagy replied on Mon, 2011/02/07 - 4:35am

About your question weather the file "META-INF/services/javax.annotation.processing.Processor" entries could contain another entry or no; simple answer is yes.

For more info, please refer to here , here and here

Mohamed El-beltagy replied on Mon, 2011/02/07 - 8:16am in response to: Mohamed El-beltagy

I've been playing around with the processor and the example you mentioned.

I tried to add more than one processor in the JAR and I found out, according to the Processor.process java doc that you need to return false instead of true (in you example).

This is when I tried to register a processor with the depricated annotations running with the Silly processor you introduced.

When making both processors return false; both processors run well.

Carl-petter Bertell replied on Tue, 2011/02/08 - 1:19am

Thanks for the clarification.

So if we're returning true from process subsequent processors which match the same supported annotation types will not be called.

In this example we match all annotations and even classes w/o annotations: @SupportedAnnotationTypes(value= {"*"})

So it essentially claims them all.

Thomas Kern replied on Thu, 2012/09/06 - 10:48am

Thanks, this is exactly what I was looking for–the smallest possible example of adding custom annotation processing to Eclipse.

http://www.java-tips.org 

James Walker replied on Sun, 2012/10/14 - 7:04am

I made one very contrived example of java6 processor usage with Eclipse. All of this is possible to integrate into a maven build but I’m leaving that out and focusing on how I got this processing to work within Eclipse Steamer's Carpet Care

Zem Karlos replied on Thu, 2012/11/15 - 10:07pm

 Very helpful tutorial....thanbks for shearing...Austin personal injury lawyer

Zem Karlos replied on Sun, 2012/12/16 - 1:56pm

 Thanks for sharing nice information with us. i like your post and all you share with us is update and quite informative,thanks for sharing............Greenspoint Dental

Zem Karlos replied on Wed, 2013/05/08 - 11:28am

Indeed a nice post to have come across, I must admit that you have done a great work.... pinless calling cards

Zem Karlos replied on Sat, 2013/05/25 - 12:43pm

Interesting post and thanks for sharing. Some things in here I have not thought about before. Thanks for making such a cool post which is really very well written. I will be referring a lot of friends about this...kerry wedding photographer

Zem Karlos replied on Sat, 2013/06/01 - 1:10am

 
Just saying thanks will not just be enough, for the exceptional lucidity in your writing.fiberglass cloth

Zem Karlos replied on Sun, 2013/06/02 - 11:40pm

Orlando Roof repair  I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites website list and will be checking back soon. Please check out my site as well and let me know what you think.

Zem Karlos replied on Sun, 2013/11/10 - 5:46pm

Roof repair Specialist  Hello very nice website!! Guy .. Excellent .. Superb .. I will bookmark your blog and take the feeds also...I'm glad to seek out so many helpful information here within the post, we need work out extra strategies in this regard, thanks for sharing.

 

Richaard Matias replied on Sun, 2014/03/16 - 9:08am

this post very helpfull, thanks. visit our page: Jual Online Printer Epson L-Series dengan Harga TERMURAH di Kawasan Indonesia Timur  ok..

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.