/ ANNOTATIONS, REFLECTION, VAADIN

Listing annotated classes in Java EE

The Java EE platform is huge, and I must confess I’m not aware of every nook and cranny of its recent API. Lately, I learned a new trick.

I was working on the version 10 of the Vaadin framework also known as Vaadin Flow. This version introduces routes: a route is a path/component pair. When a path is requested, the Vaadin Servlet displays the component. Routes are created by annotating specific components with the @Route annotation. Thus, Vaadin needs to create route objects at startup time. And for that, it needs to list all classes annotated with @Route.

To achieve that, Java EE offers the following:

@HandlerTypes

This annotation lists all other annotation classes the container must look for.

ServletContainerInitializer

Implementations of this interface will be scanned by the platform. It must be annotated by the former annotation, with the list of annotations to look for. Then, its onStartup(c: Set<Class<?>>, ctx: ServletContext) method will be invoked by the platform. The set will be filled with classes that were found.

Vaadin makes use of it like this:

class diagram

Here is a code excerpt:

RouteRegistryInitializer.java
@HandlesTypes({ Route.class, RouteAlias.class })
public class RouteRegistryInitializer extends AbstractRouteRegistryInitializer
        implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> classSet, ServletContext servletContext)
            throws ServletException {
         // Redacted for brevity's sake
    }
}

The platform will call the onStartup() method, and the classSet will be filled with every class annotated with either @Route or @RouteAlias.

Nicolas Fränkel

Nicolas Fränkel

Nicolas Fränkel is a technologist focusing on cloud-native technologies, DevOps, CI/CD pipelines, and system observability. His focus revolves around creating technical content, delivering talks, and engaging with developer communities to promote the adoption of modern software practices. With a strong background in software, he has worked extensively with the JVM, applying his expertise across various industries. In addition to his technical work, he is the author of several books and regularly shares insights through his blog and open-source contributions.

Read More
Listing annotated classes in Java EE
Share this