Skip to content

Instantly share code, notes, and snippets.

@LordMZTE
Last active June 20, 2020 14:15
Show Gist options
  • Save LordMZTE/bb55613ab21030d0e450353ffccf267f to your computer and use it in GitHub Desktop.
Save LordMZTE/bb55613ab21030d0e450353ffccf267f to your computer and use it in GitHub Desktop.
Injecting Instrumented classes to classpath at runtime with javaassist
package de.mzte.test;
public class InstrClass {
public static void sayHello() {
System.out.println("Hello!");
}
}
package de.mzte.test;
import javassist.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws NotFoundException, CannotCompileException, IOException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
//Instrument class
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("de.mzte.test.InstrClass");
CtMethod m = cc.getDeclaredMethod("sayHello");
m.insertBefore("System.out.println(\"Someone Said Hello!\");");
cc.defrost();
cc.writeFile();
//Inject class into classpath
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
Method method = ClassLoader.class.getDeclaredMethod("addClass", Class.class);
method.setAccessible(true);
method.invoke(classLoader, cc.toClass());
//Call Like normal
InstrClass.sayHello();
InstrClass.sayHello();
InstrClass.sayHello();
InstrClass.sayHello();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment