Build.gradle can't find task class defined in an "apply from" external script

I have written a custom task in a external build script ( ‘customTask.gradle’ ) and I apply that script to my main script ( ‘build.gradle’ ) via the apply from: ‘customTask.gradle’ mechanism. Assuming my custom task is called CustomTask, I am unable to consume it in the main script like:

task greet (type: CustomTask) {
 greeting 'hello from build.gradle'

Trying to evaluate the project results in a configuration phase error, root cause:

Caused by: groovy.lang.MissingPropertyException: Could not find property 'CustomTask' on root project 'myproj'.

However, if I move the task declaration to the customTask.gradle, it works fine.

Can some one please explain what the difference is? I assumed that the apply from: ‘customTasks.gradle’ was a simple include type mechanism and wouldn’t have any differences in terms of dependencis or scoped names. But clearly it does.

See Uer Guide section 57.1.

However, the task class is not visible outside the build script, and so you cannot reuse the task class outside the build script it is defined in.

Instead of trying to import custom task with apply, you can add it to your buildSrc/ dir. Gradle will build/import any custom tasks you place in this location.

Thanks Casey! I do know about the buildSrc option, and I have a reason for avoiding that solution. I’m mostly interested in the mechanics of my chosen path. Perhaps i just need an import statement?

The different scripts have different class loaders. This is necessary (and desirable) for a few reasons, primarily that the plugin application happens at runtime.

A solution here is to use the type as a class literal value. In your class defining script, add the class as an extra property to the project ‘ext.MyTaskClass = MyTaskClass’. Then you can refer to the class as that variable in the calling script.