无需严格编译即可为 CtCodeSnippetStatement 构建 Spoon CtElement

问题描述

有没有办法在不完全编译的情况下为 CtCodeSnippetStatement 构建 CtElement?我有一些片段,我希望能够对其进行扫描和进一步处理,然后再将它们插入到具有其余依赖项(片段可能引用的方法/全局变量)的类中。

解决方法

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

ValueError

这里使用了一个没有输入资源的环境,它将阻止系统类加载器访问类路径。 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(); 中的元素将返回 compiledStatementnull,并返回 getDeclarationnull 以访问用户定义的类。