Search code examples
classmavenclassloadermaven-pluginmaven-3

Maven plugin loading classes


I have an application which has legacy Struts actions extending org.apache.struts.StrutsActions. I would like to be sure that all my classes which are extending StrutsActions have a custom annotation.

In order to provide this I have written a small maven enforcer rule to validate my requirement. However I dont know how to load my classes at my mojo to validate them.

Actually I have done something not fancy which is injection outputDirectory and with a custom class loader I have recursively loaded all classes at my build folder.

Thanks


Solution

  • I have done it with the help of reflections

      <dependency>
         <groupId>org.reflections</groupId>
         <artifactId>reflections</artifactId>
         <version>0.9.5</version>
      </dependency>
    

    my implementation is like this:

    public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException {
    
        URL url = getURL(helper.evaluate("${project.build.outputDirectory}"));
    
        Predicate<String> filter = new FilterBuilder().include(getTargetSuperTypeForSubtypes());
        Predicate<String> filter2 = new FilterBuilder().include(getMustHaveAnnotation());
    
        Reflections reflections = new Reflections(new ConfigurationBuilder()
         .setScanners(
            new TypeAnnotationsScanner().filterResultsBy(filter2),
            new SubTypesScanner().filterResultsBy(filter))
         .setUrls(url));
    
        validate(reflections);
    }