Skip to content

Instantly share code, notes, and snippets.

@raphw
Created October 11, 2016 15:10
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/d90ff0fcc13554872250e9d459c288d4 to your computer and use it in GitHub Desktop.
Save raphw/d90ff0fcc13554872250e9d459c288d4 to your computer and use it in GitHub Desktop.
Dead code without return sample.
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class Foo {
public static void main(String[] args) throws Exception {
Class<?> type = new ByteBuddy()
.redefine(Bar.class)
.visit(new AsmVisitorWrapper.ForDeclaredMethods().method(named("bar"), new AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper() {
@Override
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription.InDefinedShape instrumentedMethod,
MethodVisitor methodVisitor,
final ClassFileVersion classFileVersion,
int writerFlags,
int readerFlags) {
return new MethodVisitor(Opcodes.ASM5, methodVisitor) {
@Override
public void visitLdcInsn(Object cst) {
if (cst.equals("foo")) { // Dummy check to see that the actual class was loaded.
cst = "bar";
}
super.visitLdcInsn(cst);
}
@Override
public void visitInsn(int opcode) {
super.visitInsn(opcode);
if (opcode == Opcodes.RETURN) {
mv.visitLdcInsn("qux");
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
}
}
};
}
}))
.make()
.load(null)
.getLoaded();
type.getDeclaredMethod("bar").invoke(type.newInstance());
}
public static class Bar {
public void bar() {
System.out.println("foo");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment