0

I have made a plugin with a task that will search the classpath for classes annotated with a specific annotation, using the Reflections library from google (here). However, when consuming the plugin and running the task, the current modules' classpath is not used. How can I get the task to look at the output from the jar task (from the java plugin) as on the classpath?

Here is my example plugin:

package com.myplugin;

import org.gradle.api.Plugin;
import org.gradle.api.Project;

public class MyPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {
        project.getTasks().create("myplugintask", MyPluginTask.class);
    }
}

My Task Code:

package com.myplugin;

import lombok.Data;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
import org.reflections.Reflections;

public class MyPluginTask extends DefaultTask {
    @TaskAction
    public void reflect() {
        Reflections reflections = new Reflections("com.consumer.reflected");

        for (Class<?> clazz : reflections.getTypesAnnotatedWith(Data.class)) {
            getLogger().info(clazz.toString());
        }
    }
}

And my consuming project has a class:

package com.consumer.reflected;

import lombok.Data;

@Data
public class SomeClass {
}

I would expect to be able to run:

gradle myplugintask

And see the SomeClass, but reflections returns zero results.

Note: I have tried implementating an instantiation of the plugin (and task) inside of the consumer project, and ran it as a standard jar, and that succeeds (output shows SomeClass)

Samuel Raghunath
  • 155
  • 1
  • 13

1 Answers1

2

In a nutshell, the task class needs an @InputFiles Iterable<File> classpath property, the plugin needs to configure this property (e.g. myTask.classpath = project.sourceSets.main.compileClasspath), and the task action needs to somehow pass the class path to the reflections library. I'm sure you can work out the rest.

Peter Niederwieser
  • 121,412
  • 21
  • 324
  • 259
  • Thanks Peter! I will look into it! I am slightly confused on how to get sourceSets.main.compileClasspath assigned to the plugin, when the plugin is java-based. Does that reside on the project object somewhere? Or can that only be assigned by the consuming project? – Samuel Raghunath Apr 08 '14 at 15:30
  • In Java it's somewhat harder: `SourceSet mainSourceSet = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName("main")`. Before getting the source set, your plugin should apply the Java plugin, to make sure that the source set has already been added. – Peter Niederwieser Apr 08 '14 at 15:35