Maven compiler, only compile annotated classes

1.4k views Asked by At

I've created a custom Java annotation (code below) in a Maven 2 project I'm working on:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MYANNOTATION{}

At one part of the Maven build, I only want to compile classes annotated with this annotation, e.g:

@MYANNOTATION
public class MyClass {
    // Code here
}

I'm currently using the Maven Compiler Plugin to restrict complication based on package structure. My pom.xml contains resembles the one below, restricting compilation to classes in **com.foo.bar.stuff** and **com.baz.foo.more**. This is unsatisfactory, because when I add annotated classes to com.xyz.bar.foo, I must remember to define it in the pom.

<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <executions>
          <execution>
            <id>default-compile</id>
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
            <configuration>
              <includes>
                <include>**/com/foo/bar/stuff/**</include>
                <include>**/com/baz/foo/more/**</include>
              </includes>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

Is there any way to define Maven to compile only classes that have been annotated with this annotation, not depending on where they are located in the package hierarchy?

(I'm trying to generate a metamodel from domain model classes so I can point to fields & methods without defining the names as String constants - and changing them manually when I refactor)

Edit: I am already doing annotation processing in another part of the build phase. The system works like this:

  1. Compile classes in the specified packages
  2. Using JAnnocessor, build metamodels from classes with @MYANNOTATION
  3. Compile the rest of the classes

Dependencies from other classes to the metamodel classes prevent compiling everything in one go, unless we move the annotated classes to a different project and add a dependency to it. That's one possibility but can add complexity, because the current project structure appears to form a logical whole.

1

There are 1 answers

0
Sean Patrick Floyd On

You can do something similar to what you want with annotation processing. I don't think there's any maven-specific thing you need to do, but you need to write an annotation processor that has to either be part of a separate library or compiled separately.

The concept of annotation processing is explained pretty well in this blog entry:

Code Generation using Annotation Processors in the Java language – part 2: Annotation Processors