]> git.somenet.org - pub/jan/dst18.git/blob - ass2-di/src/main/java/dst/ass2/di/agent/InjectorAgent.java
[2.2.2] Transparent DI works.
[pub/jan/dst18.git] / ass2-di / src / main / java / dst / ass2 / di / agent / InjectorAgent.java
1 package dst.ass2.di.agent;
2
3 import dst.ass2.di.annotation.Component;
4 import javassist.*;
5
6 import java.io.ByteArrayInputStream;
7 import java.io.IOException;
8 import java.lang.instrument.ClassFileTransformer;
9 import java.lang.instrument.IllegalClassFormatException;
10 import java.lang.instrument.Instrumentation;
11 import java.security.ProtectionDomain;
12
13 public class InjectorAgent implements ClassFileTransformer {
14     public static void premain(String args, Instrumentation instrumentation) {
15         instrumentation.addTransformer(new InjectorAgent());
16     }
17
18     @Override
19     public byte[] transform(ClassLoader loader, String className,
20                             Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
21                             byte[] classfileBuffer) throws IllegalClassFormatException {
22
23         ClassPool classPool = new ClassPool();
24         classPool.appendClassPath(new LoaderClassPath(loader));
25         try {
26             CtClass ctClass = classPool.makeClass(new ByteArrayInputStream(classfileBuffer));
27
28
29             // only @Components may continue.
30             if (!ctClass.hasAnnotation(Component.class)) {
31                 return classfileBuffer;
32             }
33
34             // insert our code into constructors
35             for (CtConstructor ctor : ctClass.getConstructors()) {
36                 try {
37                     ctor.insertAfter("dst.ass2.di.InjectionControllerFactory.getTransparentInstance().initialize(this);");
38                 } catch (CannotCompileException e) {
39                     e.printStackTrace();
40                     return classfileBuffer;
41                 }
42             }
43
44             // output new bytecode.
45             return ctClass.toBytecode();
46         } catch (IOException | CannotCompileException e) {
47             e.printStackTrace();
48             return classfileBuffer;
49         }
50     }
51 }