Possible to conditionally apply a plugin to a subproject?

I’ve written a plugin such that when applied, the main task will be depended on by compileJava, and the task will generate some code that will be compiled by compileJava. This plugin should only be used if certain kinds of source files are used in the project.

It’s easy enough to apply the plugin in standalone projects that I know have these source files.

In a multi-project build, I’d like to have the top-level build “conditionally apply” the plugin to each subproject, only if it sees those particular kinds of source files in the subproject (in truth, just the presence of a particular named folder should suffice). The result would be, if I ran my build in the subproject, which now has a very minimal build.gradle file, it will run the task from the plugin to generate code, and it will compile that code along with the hand-written code, without having to specify the plugin in the subproject’s build.gradle file.

Is this possible and reasonable to do?