Skip to content

Instantly share code, notes, and snippets.

@raphw
Created May 9, 2019 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphw/1a87fa3541caf011feb4e6fc66824af2 to your computer and use it in GitHub Desktop.
Save raphw/1a87fa3541caf011feb4e6fc66824af2 to your computer and use it in GitHub Desktop.
Class remapper ASM/Byte Buddy example
package x;
public class Bar extends Foo {
@Override
public void m() {
System.out.println("bar");
}
}
import static net.bytebuddy.matcher.ElementMatchers.named;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.commons.ClassRemapper;
import org.objectweb.asm.commons.SimpleRemapper;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.field.FieldList;
import net.bytebuddy.description.method.MethodList;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.pool.TypePool;
import net.bytebuddy.utility.JavaModule;
import x.Qux;
class Demo {
public static void main(String[] args) {
new AgentBuilder.Default()
.with(AgentBuilder.Listener.StreamWriting.toSystemError().withTransformationsOnly())
.with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
.type(named("x.Qux"))
.transform((builder, typeDescription, classLoader, module) -> builder.visit(new AsmVisitorWrapper.AbstractBase() {
public ClassVisitor wrap(
TypeDescription instrumentedType, ClassVisitor classVisitor,
Implementation.Context implementationContext, TypePool typePool,
FieldList<FieldDescription.InDefinedShape> fields, MethodList<?> methods,
int writerFlags, int readerFlags
) {
return new ClassRemapper(classVisitor, new SimpleRemapper("x/Foo", "x/Bar"));
}
}).installOn(ByteBuddyAgent.install());
new Qux().demo();
}
}
package x;
public class Foo {
public void m() {
System.out.println("foo");
}
}
package x;
public class Qux {
public void demo() {
new Foo().m();
}
}
@homedirectory
Copy link

Glad to have found this example, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment