0

I wrote a gradle plugin where I do expect to access sources of the project and generate some files. Everything works when I run my project from Java, however when I try to do the same via plugin it does not work. It does not see the sources of the project.

Is it true, that in gradle, sources are not visible to buildscript and therefore to plugin as well? Is it possible to make them available for the plugin?

This class is used to get the list of classes.

public class ClassFinder {
    private final List<? extends Class<?>> classes;

    public ClassFinder(String packageToScan) {
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));
        Set<BeanDefinition> classes = provider.findCandidateComponents(packageToScan);

        this.classes = classes.stream()
                .map(bean -> {
                    try {
                        return Class.forName(bean.getBeanClassName());
                    } catch (ClassNotFoundException e) {
                        throw new IllegalStateException(e);
                    }
                })
                .collect(Collectors.toList());
    }

    ...
}

I can use it either in main method or in plugin. In main it finds all the classes in my current project. In plugin it does not find anything (except libraries).

Mariusz.v7
  • 2,322
  • 2
  • 16
  • 24

1 Answers1

1

What you are referring to are not source files, but already compiled classes on the current classpath. Since Gradle compiled those classes, it is clear that they cannot appear on the classpath of the Gradle runtime and its plugins. So it will be impossible to collect the classes of your production code from a Gradle plugin. However, it would be possible to use Gradle to invoke your functionality from Gradle by using an JavaExec task with the classes from the compilation task on the classpath.

Lukas Körfer
  • 13,515
  • 7
  • 46
  • 62
  • Why would it be "impossible" to load the classes, once compiled? It may not be good idea, but it is certainly possible. – Markus Rother Mar 23 '22 at 08:38
  • 1
    Maybe the term "impossible" seems a little bit to strong, as there actually is a way to load the classes dynamically once they are compiled. However, taking a look at the usual Gradle build, any plugin will be loaded **before** the compilation of the project sources, therefore the resulting classes cannot be loaded with the plugin in an easy way. – Lukas Körfer Mar 23 '22 at 09:26