Created
July 17, 2012 09:33
-
-
Save mwicat/3128337 to your computer and use it in GitHub Desktop.
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
| import java.io.File; | |
| import java.io.FileInputStream; | |
| import java.util.Scanner; | |
| import javassist.*; | |
| import uk.co.agena.minerva.util.helpers.*; | |
| class Injector | |
| { | |
| private CtClass cc; | |
| public Injector() throws Exception { | |
| ClassPool pool = ClassPool.getDefault(); | |
| pool.importPackage("uk.co.agena.minerva.util.io"); | |
| pool.importPackage("javax.swing"); | |
| pool.importPackage("java.util"); | |
| pool.importPackage("java.io"); | |
| pool.importPackage("uk.co.agena.minerva.util.helpers"); | |
| cc = pool.get("uk.co.agena.minerva.util.helpers.ProbabilityCalculator"); | |
| Scanner scanner = new Scanner(new File("randomiseProbabilities.java")).useDelimiter("\\Z"); | |
| inject("randomiseProbabilities", scanner.next()); | |
| inject("getType", "{ return \"Professional\"; }"); | |
| scanner = new Scanner(new File("compileProperties.java")).useDelimiter("\\Z"); | |
| inject("compileProperties", scanner.next()); | |
| cc.writeFile(); | |
| } | |
| private void inject(String method, String body) throws Exception { | |
| // Find the method we want to patch and rename it | |
| // (we will be creating a new method with the original name). | |
| CtMethod m_old = cc.getDeclaredMethod(method); | |
| m_old.setName( method + "$impl" ); | |
| // Create a new method with the same name as the old one | |
| CtMethod m_new = CtNewMethod.copy(m_old, method, cc, null); | |
| // Provide the new method's implementation | |
| StringBuilder sb = new StringBuilder(); | |
| sb.append(body); | |
| m_new.setBody( sb.toString() ); | |
| // Add the new method to the class. Patch the .class file | |
| cc.addMethod( m_new ); | |
| } | |
| public static void main(String[] argv) throws Exception | |
| { | |
| new Injector(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment