在没有严格编译的情况下为 CtCodeSnippetStatement 构建 Spoon CtElements

Building Spoon CtElements for a CtCodeSnippetStatement without strict compiling

有没有办法在不完全编译的情况下为 CtCodeSnippetStatement 构建 CtElement?在将它们与其余依赖项(代码段可能引用的方法/全局变量)一起插入 class 之前,我希望能够扫描和进一步处理代码段。

如果您所说的“未完全编译”意味着您不希望 Spoon 解析已编译代码段中的类型引用,那么您可以尝试:

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();

这里使用了一个没有输入资源的环境,它会阻止系统类加载器访问类路径。 compiledStatement 中的元素将 return nullgetDeclaration 和 return nullgetTypeDeclaration 用于访问用户定义的 类.