'How to call a external library class from JavaExec?

I'm writing a prebuild Gradle plugin in Groovy. My project structure is as following:

+ buildSrc
| + src
| |  - main
| |     - groovy
| |        - org
| |           - domain
| |              + MyPlugin.groovy
| |              - MyPluginTask.groovy
| - build.gradle
+ build.gradle
- settings.gradle  

What I would like to achieve is to write a prebuild plugin (this is why it's in buildSrc), that has a dependency. When someone will be using this plugin, one will not need to download this dependency on its own. The plugin will define a task, which will execute a Java class from this external dependency.

My buildSrc/build.gradle:

plugins {
    id 'groovy-gradle-plugin'
}

group = 'org.domain'
version = '0.1.0'

repositories {
    mavenCentral()
}

dependencies {
    implementation group: 'org.example', name: 'external-package', version: '1.0.0'
}

gradlePlugin {
    plugins {
        myPlugin {
            id = 'org.domain.my-plugin'
            implementationClass = 'org.domain.MyPlugin'
        }
    }
}

My build.gradle:

plugins {
    id 'org.domain.my-plugin'
}

What I have a problem is, that from examples and code found on the Internet, I saw that I need to use a sourceSets.main.classpath. The problem is, it's not available from Groovy class. I saw that it's only available from DSL. I saw that someone used it from project convention, but according to Gradle docs, the convention is deprecated, and should not be used.

My MyPluginTask.groovy:

package org.domain

import org.gradle.api.tasks.JavaExec;

class MyPluginTask extends JavaExec {

    public MyPluginTask() {
        setGroup("MyPlugin");
        setDescription("My plugin description");
        // from what I understand I need to set a classpath here, but I don't know how to do it
        // setClasspath(' ????? ');
        mainClass.set("org.example.external-package.Main");  // <-- this is what I understand I need to do?
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source