Is there a way to get all dependencies of a custom configuration in a Gradle plugin?

I have a Gradle plugin where I have a custom configuration, and I am trying to get all dependencies of said configuration. However, my current code does not print anything to console.

Here is my code:

public class TestPlugin implements Plugin<Project>
{
    public static final String VERSION = "1.0.0";

    @Override
    public void apply(Project project)
    {
        project.getLogger().lifecycle("TestPlugin: " + VERSION);
        Configuration testConfig = project.getConfigurations().create("testConfig");

        for(Dependency dependency : testConfig.getDependencies())
        {
            project.getLogger().lifecycle(" " + dependency.getName());
        }
    }
}

I have no idea why this code does not work, “TestPlugin: 1.0.0” prints to console fine so it is not a console problem. I am new to Gradle plugins, am I doing this wrong?

Thanks for help in advance

I think your problem is timing, you’re calling Configuration.getDependencies() before it’s been configured. Most gradle collections support “live” methods which receive events for future configurations. Try

testConfig.dependencies.all { dep
   doStuff(dep) 
} 

See DomainObjectCollection.all(Closure)

Thanks for the help. However, I am writing the plugin in Java, so is there a way to do this in Java, not Groovy?

Edit: Nevermind, I found a solution after reading your reply properly. To anyone reading this in the future you should add a ProjectEvaluationListener and get the list of dependencies after evaluation .

Using the after evaluate event is hacky, much better to react to events as they happen on the collection instead.

I am writing the plugin in Java, so is there a way to do this in Java

You can use DomainObjectCollection.all(Action<T>)

Sorry for the late reply, but how would I use DomainObjectCollection.all(Action) ?

Thanks

Rather than getting the dependencies and iterating through what’s there when your plugin is applied, you would put your logic in the Action provided to all(). The simplest case (using what you had and the suggestion asked about) could look like the following:

public class TestPlugin implements Plugin<Project> {

    public static final String VERSION = "1.0.0";

    @Override
    public void apply(Project project) {
        project.getLogger().lifecycle("TestPlugin: " + VERSION);
 
        Configuration testConfig = project.getConfigurations().create("testConfig");

        testConfig.getDependencies().all(dependency -> {
            project.getLogger().lifecycle(" " + dependency.getName());
        });
    }
}

However, there might be better ways to accomplish your actual requirement later in the lifecycle. I expect the printing is just for testing and not really what you’re doing with the dependencies.

Thanks, and yes, the printing is just for testing.