Skip to content
Advertisement

Intellij Code Inspection for Custom Annotation

One of the problems I’ve encountered while using DTOs is that I often find myself shipping (accidentally) entities along with DTOs. To mitigate this problem, I created another Maven project with an annotation (@ValidDTO) and its processor that finds if a DTO annotated with @ValidDTO has @Entity annotated fields.

This is my annotation.

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface ValidDTO {}

And, this is my processor.

@SupportedAnnotationTypes("com.aj.annotations.ValidDTO")
@SupportedSourceVersion(SourceVersion.RELEASE_11)
public class ValidDTOProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> set,
                           RoundEnvironment roundEnv) {

        List<Entity> entityFields = roundEnv.getElementsAnnotatedWith(ValidDTO.class)
                .stream()
                .filter(element -> element.getKind()==ElementKind.CLASS || element.getKind()==ElementKind.INTERFACE)
                .map(Element::getEnclosedElements)
                .flatMap(List::stream)
                .filter(element -> element.getKind()==ElementKind.FIELD)
                .map(element -> element.getAnnotation(Entity.class))
                .collect(Collectors.toList());

            if (!entityFields.isEmpty()) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Types annotated with ValidDTO " +
                    "cannot have member variables that are @Entity annotated");
        }

        return true;
    }
}

This is how my POM.xml looks for the Maven project with the annotation and its processor

 <groupId>com.aj</groupId>
    <artifactId>aj-annotations</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                    <generatedSourcesDirectory>${project.build.directory}/generated-sources/
                    </generatedSourcesDirectory>
                    <proc>none</proc>
                    <annotationProcessors>
                        <annotationProcessor>
                            com.aj.annotations.processors.ValidDTOProcessor
                        </annotationProcessor>
                    </annotationProcessors>
                    <debug>true</debug>
                </configuration>
            </plugin>
        </plugins>
    </build>

So, I installed this package as a dependency in another projected and annotated a DTO with it. I purposefully added couple of entities as member variables to see the error.

@ValidDTO
public class FacilityDTO {
  private User user;
  private List<User> users;
}

where,

@Entity
@Table("User")
public class User {} 

is an entity.

Now, my custom annotation works perfectly good when I run mvn clean install or build project. I can see the expected "Types annotated with ValidDTO cannot have member variables that are @Entity annotated" in the terminal.

However, I do not see the error in the editor of the IDE. I’ve tried both Intellij and Eclipse and I do not see any red squiggly line underneath the annotation telling me that the DTO is invalid.

The closest expected desired behavior I can reference is a compile error when using @FunctionalInterface on an interface that has more than one abstract method.

I just need help configuring my IDE. Any help is appreciated!

Advertisement

Answer

In IntelliJ you can create custom inspections. These can be used to alert you to the presence of custom search patterns in your code (https://www.jetbrains.com/help/idea/creating-custom-inspections.html).

For your case: Go to settings -> Editor -> Inspections. Activate “Structural search inspection” and add a “Search Template”:

enter image description here

(UPDATE 06/2020: “Structural search” is not under “General” anymore but is now a separate topic)

Add following structural search:

enter image description here

You may change “Severity” to “Error” to get the red squiggly lines. 🙂

enter image description here

Advertisement