Circular dependency between Gradle tasks when setting up classes to perform bytecode modifications during build

59 Views Asked by At

I want to write a Gradle task that is executed during build, which will invoke a Java class that performs bytecode modifications based on logic using the ASM library.

But I'm getting this error when running build task:

Circular dependency between the following tasks:
:classes
\--- :compileJava
     \--- :modifyBytecode
          \--- :classes (*)

How can I avoid this error?

build.gradle.kts:

dependencies {
  ..
  implementation("org.ow2.asm:asm:9.2")
  ..
}

tasks.register<JavaExec>("modifyBytecode") {
    main = "com.example.CustomClassFileTransformer"
    classpath = sourceSets.main.get().output
}

tasks.getByName("compileJava").dependsOn("modifyBytecode")

Inside the Java src directory this class exists which uses the ASM API:

public class CustomClassFileTransformer implements ClassFileTransformer {
    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

        // Perform modification only for the desired class
        if (className.equals("com/example/MyClass")) {
            ClassReader cr = new ClassReader(classfileBuffer);
            ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
            ClassVisitor cv = new CustomClassVisitor(cw);
            cr.accept(cv, 0);
            return cw.toByteArray();
        }

        return classfileBuffer;
    }
}
0

There are 0 best solutions below