Exchange the task of a gradle plugin

Let’s suppose a plugin creates the following task graph:

A -> B -> C

A depends on B which depends on C.

How can I exchange the task B with another task, let’s say X to get a task graph like that?

A -> X -> C

Actually, the idea that I have to solve this problem, is to get a list of all tasks which B depends on and a list of all tasks that have B as dependency. This can be done when the graph is ready.

task C {
    doLast {
        println('Task C')
    }
}

task B {
    doLast {
        println('Task B')
    }
    dependsOn C
}

task A {
    doLast {
        println('Task A')
    }
    dependsOn B
}

gradle.taskGraph.whenReady { graph ->
    ext.b_dependsOn = graph.allTasks.findAll { it.name == 'B' }.each {
        println("Found task $it.name")
        println("which dependsOn: $it.dependsOn")
    }

    task X {
        doLast {
            println('Task X')
        }
        dependsOn b_dependsOn
    }

    ext.other_dependsOn_b = graph.allTasks.findAll { it.dependsOn.findAll { it.name == 'B' } }.each {
        println("Found a task that dependsOn B: $it.name")
        it.dependsOn X
    }
}

The next step is then to make task X depends on the task of B and make all other tasks, that had B as dependency, depend from X.

Now when I execute gradle a, X is not replacing B. Why?

Here the output of gradle execution:

$ gradle a
Found task B
which dependsOn: [task ':C']
Found a task that dependsOn B: A

> Task :C
Task C

> Task :B
Task B

> Task :A
Task A