我正在尝试使用janino将所有局部变量声明移至字段声明,以便在我输入以下代码
class A {
int a;
void test() {
int b = 0;
int c = 1;
b += c;
}
}
然后将其解析为CompilationUnit
,并使用Traverser
更改AST,然后将其取消解析,我可以得到
class A {
int a;
int b;
int c;
void test() {
b = 0;
c = 1;
b += c;
}
}
我编写了以下方法,从Java.FieldDeclaration
创建Java.LocalVariableDeclarationStatement
:
static Java.FieldDeclaration createFieldDecFromLocalDec(Java.LocalVariableDeclarationStatement lvds) {
Java.Modifiers modifiers = lvds.modifiers;
Java.Type type = lvds.type;
Java.VariableDeclarator[] declarators =
new Java.VariableDeclarator[lvds.variableDeclarators.length];
for (int i = 0; i < declarators.length; i++) {
Java.VariableDeclarator oldDec = lvds.variableDeclarators[i];
declarators[i] = new Java.VariableDeclarator(
Location.NOWHERE, oldDec.name, oldDec.brackets, null);
}
return new Java.FieldDeclaration(
Location.NOWHERE, null, lvds.modifiers, lvds.type, declarators);
}
但是当我运行代码时,出现以下异常:
org.codehaus.janino.JaninoRuntimeException: Enclosing scope already set for type "int" at File 'codegen', Line 5, Column 8
如何摆脱这个例外?或者如何使用janino实现我的目标?谢谢。