MimicCreator { public void mimicConstructors(CtClass src, CtClass dst) throws CannotCompileException, NotFoundException { for (final CtConstructor constructor : src.getDeclaredConstructors()) { log.fine("Mimic constructor " + constructor.getName()); boolean destHasSameConstructor = false; for (CtConstructor constructorInDest : dst.getDeclaredConstructors()) { String signature = constructor.getSignature(); String signatureInDest = constructorInDest.getSignature(); if (signatureInDest.equals(signature)) { destHasSameConstructor = true; log.fine("Forwarding " + constructor.getName()); String key = this.key == null ? "" : (this.key + "_"); final String copiedConstructorName = "_copy_" + key + constructor.getName(); dst.addMethod(constructor.toMethod(copiedConstructorName, dst)); StringBuffer buffer = new StringBuffer(); for (int j = 0; j < constructor.getParameterTypes().length; j++) { buffer.append(" $"); buffer.append(j + 1); buffer.append(","); } String params = buffer.toString(); if (params.length() > 0) { params = params.substring(0, params.length() - 1); } String string = copiedConstructorName + "(" + params + ");\n"; log.fine("Injected constructor " + string); constructorInDest.insertAfter(string); } } if (!destHasSameConstructor) { log.fine("Copying " + constructor.getName()); dst.addConstructor(CtNewConstructor.copy(constructor, dst, null)); } } } MimicCreator();  MimicCreator(String key); boolean hasField(CtClass clazz, CtField field); boolean hasInterface(CtClass dst, CtClass interfazz); void mimicClass(CtClass src, CtClass dst, MimicMode defaultMimicMode, MimicMethod[] mimicMethods); void mimicConstructors(CtClass src, CtClass dst); void mimicFields(CtClass src, CtClass dst); void mimicInterfaces(CtClass src, CtClass dst); void mimicMethods(CtClass src, CtClass dst, MimicMode defaultMimicMode, MimicMethod[] mimicMethods);  }
@Test public void testMimicConstructors() throws Exception { src.addField(new CtField(CtClass.intType, "foo", src)); src.addConstructor(CtNewConstructor.make("public Src() { foo = 2; }", src)); mimicCreator.mimicFields(src, dst); mimicCreator.mimicConstructors(src, dst); assertHasFooFieldAndConstructor(dst.toClass()); }
@Test public void testMimicConstructors_with_keys() throws Exception { mimicCreator = new MimicCreator("bar"); src.addConstructor(CtNewConstructor.make("public Src() {}", src)); dst.addConstructor(CtNewConstructor.make("public Dst() {}", dst)); mimicCreator.mimicConstructors(src, dst); assertEquals("bar", mimicCreator.getKey()); assertHasMethod(dst.toClass(), "_copy_bar_" + src.getName(), null); }
@Test public void testMimicConstructors_with_same_constructor_with_params() throws Exception { mimicCreator = new MimicCreator("bar"); src.addConstructor(CtNewConstructor.make("public Src(int a) {}", src)); dst.addConstructor(CtNewConstructor.make("public Dst(int a) {}", dst)); mimicCreator.mimicConstructors(src, dst); assertHasConstructor(dst, dst.toClass(), new CtClass[] { CtClass.intType }); }