protected Map<Statement, Double> buildCodeFragmentFor(CtType cl, Coverage coverage) { Factory factory = cl.getFactory(); Map<Statement, Double> codeFragments = new LinkedHashMap<>(); for (CtMethod<?> mth : (Set<CtMethod>) cl.getMethods()) { if (!mth.getModifiers().contains(ModifierKind.ABSTRACT) && !mth.getModifiers().contains(ModifierKind.PRIVATE)) { // && getCoverageForMethod(coverage, cl, mth) != 1.0) { CtExecutableReference executableRef = factory.Executable().createReference(mth); executableRef.setStatic(mth.getModifiers().contains(ModifierKind.STATIC)); CtInvocation invocation = factory.Code().createInvocation(buildVarRef(cl.getReference(), factory), executableRef); invocation.setArguments( mth.getParameters() .stream() .map(param -> buildVarRef(param.getType(), factory)) .collect(Collectors.toList())); invocation.setType(mth.getType()); Statement stmt = new Statement(invocation); codeFragments.put(stmt, getCoverageForMethod(coverage, cl, mth)); } } return codeFragments; }
@Test public void testSearchMethodWithGeneric() throws Exception { CtType<Tacos> aTacos = buildClass(Tacos.class); CtMethod<Object> method1 = aTacos.getMethod("method1", aTacos.getFactory().Type().integerType()); assertEquals( "public <T extends java.lang.Integer> void method1(T t) {" + System.lineSeparator() + "}", method1.toString()); method1 = aTacos.getMethod("method1", aTacos.getFactory().Type().stringType()); assertEquals( "public <T extends java.lang.String> void method1(T t) {" + System.lineSeparator() + "}", method1.toString()); method1 = aTacos.getMethod("method1", aTacos.getFactory().Type().objectType()); assertEquals( "public <T> void method1(T t) {" + System.lineSeparator() + "}", method1.toString()); }
public CtStatement apply(CtType<?> targetType) { CtClass<?> c; Factory factory; // we first need a factory if (targetType != null) { // if it's template with reference replacement factory = targetType.getFactory(); } else { // else we have at least one template parameter with a factory factory = getFactory(); } c = factory.Class().get(this.getClass()); if (c == null) { c = factory.Class().get(this.getClass()); } // we substitute the first statement of method statement CtStatement result = factory.Core().clone(c.getMethod("statement").getBody().getStatements().get(0)); new SubstitutionVisitor(factory, targetType, this).scan(result); return result; }