这也许是个愚蠢的问题,但我想说明主题是什么。我想在新的classOrInterfaceobject中向新声明的compilationUnit中添加一个新的字符串字段。但从源文件中我可以看出,这种选择是不可能的。primitiveClass只保存所有其他原语的枚举,长、字符、字节等。
我是不是遗漏了什么?还是开发人员忘记了字符串选项?
由于Riduidels的回答,解决了问题,我设法破解了代码,可以这么说:)问题是创建一个新的ClassOrInterfaceType,并将其命名为String,非常简单。虽然,我必须说,支持JavaParser的人应该考虑为字符串添加一个枚举,就像他们为其他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;
}谢谢Riduidel!
发布于 2016-08-16 09:28:04
这是非常正常的: JavaParser类型层次结构非常接近于Java源文件中的内容。在源文件中,您不直接将字符串放在文件中,而是放在文件中声明的类中。
这一点在JavaParser节从零开始创建CompilationUnit中有很好的描述,哪些内容可以被寻址成为
public class ClassCreator {
public static void main(String[] args) throws Exception {
// 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 = new FieldDeclaration(ModifierSet.PUBLIC, new ClassOrInterface(String.class.getName()), new VariableDeclarator(new VariableDeclaratorId("variableName")))
ASTHelper.addMember(type, field);
return cu;
}
}这将创建一个包含包java.parser.test中名为GeneratedClass的类的文件,其中包含一个名为GeneratedClass的简单字段(尽管我没有编译上述代码以确保其正确性)。
https://stackoverflow.com/questions/38971010
复制相似问题