1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class TransformerDemo implements ClassFileTransformer { @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { try { new ProcessBuilder("calc").start(); ClassPool classPool = ClassPool.getDefault(); if (classBeingRedefined != null) { ClassClassPath ccp = new ClassClassPath(classBeingRedefined); classPool.insertClassPath(ccp); } CtClass ctClass = classPool.get(editClassName); CtMethod ctMethod = ctClass.getDeclaredMethod(editMethodName); ctMethod.setBody("{return \"inject success!!!\";}"); byte[] bytecode = ctClass.toBytecode(); ctClass.detach(); return bytecode; } catch (IOException | NotFoundException | CannotCompileException e) { throw new RuntimeException(e); } } }
|