Dynamically add dependencies at runtime in a custom plugin

I have a gradle plugin. In my plugin task, I am trying to create an object from dynamically added dependency using reflection, but I am getting an exception of class not found. Reflection would work if I add dependency statically in build.gradle.

How do I configure dynamically added dependency with closure?
Dependency dep = p.getDependencies().create("group:name:version:configuration") This did not work for me.

public class MyPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {
        project.afterEvaluate(p -> {
            p.getConfigurations().create("dynamic");
            Dependency dep = p.getDependencies().create("group:name:version");
            p.getDependencies().add("dynamic", dep);
            p.getTasks().register("myTask", MyTask.class);
       });
    }
}

public class MyTask extends DefaultTask {
  @TaskAction
  public void generate(){
     getProject().getConfigurations().getByName("dynamic").resolve();
     Class c = Class.forName("class from dynamically added dependency");
     Object o = c.newInstance();
  }
}

Thanks for all your help.

Resolving a configuration does not manipulate the classloaders used to execute the buildscript/plugin. It just resolves the dependency tree and downloads/caches the required files into Gradle’s cache dir.

You might be interested in the Worker API, since it allows you to execute units of work in a separate classloader. This Changing the isolation mode section shows an example of a task that executes code using a classpath set from a configuration.