diff --git a/src/main/java/spoon/support/reflect/declaration/CtTypeImpl.java b/src/main/java/spoon/support/reflect/declaration/CtTypeImpl.java index c810b446498..d997691a8c3 100644 --- a/src/main/java/spoon/support/reflect/declaration/CtTypeImpl.java +++ b/src/main/java/spoon/support/reflect/declaration/CtTypeImpl.java @@ -12,6 +12,7 @@ import spoon.reflect.code.CtBlock; import spoon.reflect.declaration.CtAnnotation; import spoon.reflect.declaration.CtAnnotationType; +import spoon.reflect.declaration.CtCompilationUnit; import spoon.reflect.declaration.CtConstructor; import spoon.reflect.declaration.CtExecutable; import spoon.reflect.declaration.CtField; @@ -991,8 +992,8 @@ public boolean isArray() { @Override public String toStringWithImports() { DefaultJavaPrettyPrinter printer = (DefaultJavaPrettyPrinter) getFactory().getEnvironment().createPrettyPrinter(); - //this call applies print validators, which modifies model before printing - //and then it prints everything including package and potentially imports - return printer.printCompilationUnit(this.getPosition().getCompilationUnit()); + CtCompilationUnit cu = getFactory().createCompilationUnit(); + cu.addDeclaredType(this); + return printer.printCompilationUnit(cu); } } diff --git a/src/test/java/spoon/test/ctClass/CtClassTest.java b/src/test/java/spoon/test/ctClass/CtClassTest.java index e04cd65e7c1..43fcfdb4d21 100644 --- a/src/test/java/spoon/test/ctClass/CtClassTest.java +++ b/src/test/java/spoon/test/ctClass/CtClassTest.java @@ -31,6 +31,7 @@ import static spoon.testing.utils.ModelUtils.buildClass; import static spoon.testing.utils.ModelUtils.canBeBuilt; +import java.io.File; import java.util.Set; import org.junit.Test; @@ -261,6 +262,11 @@ public void toStringWithImports() { " }" + newLine + " }.compare(1, 2);" + newLine + "}", aClass2.toStringWithImports()); + + // contract: toStringWithImports works with a new class with no position + assertEquals("package foo;" + newLine + + "import java.io.File;" + newLine + + "class Bar extends File {}", launcher2.getFactory().createClass("foo.Bar").setSuperclass(launcher2.getFactory().Type().get(File.class).getReference()).toStringWithImports()); } @Test