Last active
June 20, 2020 14:15
-
-
Save LordMZTE/bb55613ab21030d0e450353ffccf267f to your computer and use it in GitHub Desktop.
Injecting Instrumented classes to classpath at runtime with javaassist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package de.mzte.test; | |
public class InstrClass { | |
public static void sayHello() { | |
System.out.println("Hello!"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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