How to modify java bytecode after compilation using compiler plugins?

62 Views Asked by At

I want to modify some java classes bytecode during/after compilation phase, but before packaging, in order to use custom invokedynamic bootstrap methods.

In order to do so, I have written a Java compiler plugin using the jdk.compiler module, extending com.sun.source.util.Plugin, and attached a listener that executes after bytecode generation phase, however, the jdk.compiler module's public API does not exposes any method or with reference to the bytecode stream or generated .class file.

Are there any other strategies I could follow?

So far, the code looks like this:

package plugin;

import com.sun.source.util.JavacTask;
import com.sun.source.util.Plugin;
import com.sun.source.util.TaskEvent;
import com.sun.source.util.TaskListener;

public class Main implements Plugin, TaskListener {

    @Override
    public String getName() {
        return "my-plugin";
    }

    @Override
    public void init(JavacTask task, String... args) {
        task.addTaskListener(this);
    }

    @Override
    public void finished(TaskEvent e) {
        if(TaskEvent.Kind.GENERATE.equals(e.getKind())){
            System.out.println("no byte code reference here :(");
        }
    }

    @Override
    public boolean autoStart() {
        return true;
    }
}
0

There are 0 best solutions below