public CompilationUnit getOrCreate(CtType type) { if (type == null) { return null; } if (type.getPosition().getCompilationUnit() != null) { return type.getPosition().getCompilationUnit(); } if (type.isTopLevel()) { CtModule module; if (type.getPackage() != null && factory.getEnvironment().getComplianceLevel() > 8) { module = type.getPackage().getParent(CtModule.class); } else { module = null; } File file = this.factory.getEnvironment().getOutputDestinationHandler().getOutputPath(module, type.getPackage(), type).toFile(); try { String path = file.getCanonicalPath(); CompilationUnit result = this.getOrCreate(path); result.addDeclaredType(type); type.setPosition(this.factory.createPartialSourcePosition(result)); return result; } catch (IOException e) { throw new SpoonException("Cannot get path for file: " + file.getAbsolutePath(), e); } } else { return getOrCreate(type.getTopLevelType()); } }
/** * Save on disk Source code file Should be configured before: * .getSpoonClassCompiler().updateOutput(srcOutput); * * @param type * @return */ public void generateSourceCodeFromCtClass(CtType<?> type) { // WorkArround, for cloned SourcePosition sp = type.getPosition(); type.setPosition(null); if (output == null || output.getJavaPrinter() == null) { throw new IllegalArgumentException("Spoon compiler must be initialized"); } output.saveSourceCode((CtClass) type); // -- // End Workarround type.setPosition(sp); }