How to compile against a jar instead of directories of classes?

OK, so after sleeping on this issue, it looks like the solution is:

myConfiguration
    .withDependencies { deps ->
        // Add some extra dependencies programmatically.

        // And then set their LibraryElements attribute to JAR.
        deps.filterIsInstance(ModuleDependency::class.java).forEach { dep ->
            dep.attributes { attrs ->
                attrs.attribute(LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements::class.java, JAR))
            }
        }
    }

This does at least appear to give consistent results. All of my earlier efforts looked like Gradle was randomly selecting either JAR or CLASSES, irrespective of whatever other code changes I was making.

Does anyone who is more familiar with this than me have anything to add, please?
Thanks,
Chris