jMDA Core Makes JSR 269 Annotation Processing a Breeze With Tasks
An annotation processor is basically a class that does two things:
- It defines which annotations it is interested in (supported annotations) and
- it implements a process method that will be called by javac during compilation.
JMDA core facilitates some rather unwieldy aspects of working with bare JSR 199 and JSR 269 and brings a lot of additional support for typical annotation processing operations. For example instead of defining a full blown custom annotation processor class you can create and configure a Task instance which is much easier to do. To execute your task you simply hand it over to a TaskRunner which does all the work required to configure and run javac together with an annotation processor. Let's demonstrate this in a Hello World example:
package
de.jmda.sample.mproc.task;
import
static
de.jmda.util.CollectionsUtil.asSet;
//
… further import statements
omitted
public
class
JUTHelloWorldTypeElementTask
{
private
class
SampleTask
extends
AbstractTypeElementsTaskTypes
{
private
SampleTask(Set<?
extends
Class<?>> types)
{
super(types);
}
@Override
public
boolean
execute() throws
TaskException
{
System.out.println("Hello
World!");
for
(TypeElement type : getTypeElements())
{
System.out.println("Welcome
"
+ type.getQualifiedName() + ".");
}
return
false;
}
}
@Test
public
void
test() throws
IOException
{
SampleTask
task =
new
SampleTask(asSet(String.class));
TaskRunner.run(task);
}
}
|
- First, there is no annotation processor and no specification of supported annotations! This seems to be a contradiction to what was said to be necessary for annotation processing. In fact the task runner does this for you transparently behind the scenes so that you can focus on the processing task (the process method) itself.
- Second, we obtain access to a type element for a class, namely java.lang.String, that has no particular annotation and that comes from a .jar file for that we might not even have the source code! This means, we can obtain access to elements from any third party libraries as soon as they are available in our classpath! Again jMDA task runner does this trick for us.
- Finally, the produced output contains “Hello world!” twice. The reason for this is explained in annotation rounds explained.
No comments:
Post a Comment