AfterBurner { public void insertConstructor(InsertableConstructor insertableConstructor) throws CannotCompileException, AfterBurnerImpossibleException, NotFoundException { List<CtConstructor> constructorList = extractExistingConstructors(insertableConstructor); log.info("constructor : " + constructorList.toString()); if (!constructorList.isEmpty()) { for (CtConstructor constructor : constructorList) { constructor .insertBeforeBody(insertableConstructor .getConstructorBody(constructor .getParameterTypes())); } } else { throw new AfterBurnerImpossibleException("No suitable constructor was found in class " + insertableConstructor.getClassToInsertInto().getName() + ". Add a constructor that is accepted by the InsertableConstructor. Don't use non static inner classes."); } } AfterBurner(); void addOrInsertMethod(InsertableMethod insertableMethod); void beforeOverrideMethod(CtClass targetClass, String targetMethodName, String body); void afterOverrideMethod(CtClass targetClass, String targetMethodName, String body); void insertConstructor(InsertableConstructor insertableConstructor); CtMethod extractExistingMethod(final CtClass classToTransform,
            String methodName); boolean checkIfMethodIsInvoked(CtMethod withinMethod,
        String invokedMethod);  }
@Test public void testInsertConstructor() throws Exception { target.addConstructor(CtNewConstructor.make("public Target() {}", target)); target.addField(new CtField(CtClass.intType, "foo", target)); InsertableConstructor insertableConstructor = new SimpleInsertableConstructor(target, "foo = 2;", true); afterBurner.insertConstructor(insertableConstructor); targetClass = target.toClass(); targetInstance = targetClass.newInstance(); assertHasFooFieldWithValue(target, 2); }
@Test(expected=AfterBurnerImpossibleException.class) public void testInsertConstructor_with_no_constructor() throws Exception { target.addConstructor(CtNewConstructor.make("public Target() {}", target)); target.addField(new CtField(CtClass.intType, "foo", target)); InsertableConstructor insertableConstructor = new SimpleInsertableConstructor(target, "foo = 2;", false); afterBurner.insertConstructor(insertableConstructor); fail(); }