Search code examples
javainria-spoon

Building Spoon CtElements for a CtCodeSnippetStatement without strict compiling


Is there a way to build CtElement’s for a CtCodeSnippetStatement without fully compiling? I have snippets I’d like to be able to scan and further process, before inserting them into a class with the rest of their dependencies (methods / global variables which the snippet may reference).


Solution

  • If you by "without fully compiling" mean that you don't want Spoon to resolve type references in the compiled snippet then you can try:

    Environment env = new StandardEnvironment();
    env.setInputClassLoader(new URLClassLoader(new URL[]{}, null));
    Factory factory = new FactoryImpl(new DefaultCoreFactory(),env);
    CtCodeSnippetStatement statement = factory.createCodeSnippetStatement("pkg.MyClass myClass = new pkg.MyClass();");
    CtStatement compiledStatement = statement.compile();
    

    An environment is used here without input resources and it will prevent the system classloader from accessing the classpath. Elements in compiledStatement will return null with getDeclaration, and return null with getTypeDeclaration for accesses to user-defined classes.