这可能是一个愚蠢的问题,但我想了解主题所说的内容。我想在新的编译单元中向新声明的 classOrInterfaceobject 添加一个新的 String 字段。但是从我从源文件中可以看出,该选项是不可能的。PrimitiveClass 只保存所有其他原语的枚举,Long、char、bytes 等。
我错过了什么吗?还是开发人员忘记了 String 选项?
解决了感谢Riduidels 的回答,我设法破解了代码,可以这么说:) 事情是创建一个新的 ClassOrInterfaceType 并将其命名为 String,很简单。不过,我必须说,JavaParser 背后的人应该考虑为 String 添加一个枚举,就像他们为其他 Primitives 所做的那样。工作代码:
public static void main(String[] args){
// TODO Auto-generated method stub
// creates the compilation unit
CompilationUnit cu = createCU();
// prints the created compilation unit
System.out.println(cu.toString());
}
/**
* creates the compilation unit
*/
private static CompilationUnit createCU() {
CompilationUnit cu = new CompilationUnit();
// set the package
cu.setPackage(new PackageDeclaration(ASTHelper.createNameExpr("java.parser.test")));
// create the type declaration
ClassOrInterfaceDeclaration type = new ClassOrInterfaceDeclaration(ModifierSet.PUBLIC, false, "GeneratedClass");
ASTHelper.addTypeDeclaration(cu, type); // create a field
FieldDeclaration field = ASTHelper.createFieldDeclaration(ModifierSet.PUBLIC, new ClassOrInterfaceType("String"),"test");
ASTHelper.addMember(type, field);
return cu;
}
谢谢瑞杜德尔!