Modifying Maven pom generation to add excludes

I’m trying to manipulate the maven pom before it is generated, and having some trouble accessing the maven classes. Specificially, I want to manually add some excludes to the pom (I know I can do this through gradle dependencies, but it doesn’t quite work for what I need). So I have some code like this (not exact, just for demonstration):

project.modifyPom { MavenPom pom ->
    for (org.apache.maven.model.Dependency dep : pom.dependencies) {
        org.apache.maven.model.Exclusion exclude = new org.apache.maven.model.Exclusion()

However, running say gradle install I get a class not found exception:

Caused by: java.lang.ClassNotFoundException: org.apache.maven.model.Dependency
    ... 108 more

Similarly, if I change the assignment in the for loop to a def, I get a class not found for Exclusion. So it seems the maven classes are not accessible. Looking a little closer at MavenPom, it looks clear it was designed as to not leak the implementation detail (using Maven classes to generate the pom). However, the fact that you can setDependencies means one needs access to the actual concrete type of the dependencies list. Am I missing something? Is there another way I can add an exclude at pom generation (hopefully other than adding the xml myself in withXml)?

There’s two ways to publish to maven so it’s worth mentioning which you are using.

  1. The new (incubating) maven-publish plugin

  2. The old UploadTask based aporoach

If using option 1 you could use the pom.withXml hook to tweak the pom

See my original post. I explicitly am looking to not use pom.withXml if at all possible. I am also using the UploadTask because of issues with the maven-publish plugin.

But regardless of the publishing mechanism, the pom generation is, I believe, the same. It seems counterintuitive to try to hide maven’s api, as it is only possible, through groovy, to modify existing objects, but not create new objects (eg exclusions like I am trying to do).

You can see what I’m trying to do here: