[英]Adding a String field to a new compilationUnit with JavaParser
这可能是一个愚蠢的问题,但我想了解一下主题的内容。 我想在新的新compilationUnit中向新声明的classOrInterfaceobject添加一个新的String字段。 但是从我从源文件中可以看出来,该选项是不可能的。 PrimitiveClass仅包含所有其他原始类型的枚举(长整数,字符,字节等)。
我想念什么吗? 还是开发人员忘记了String选项?
已解决感谢Riduidels的回答,可以说,我设法破解了代码:)要做的是创建一个新的ClassOrInterfaceType并将其命名为String,非常简单。 但是,我必须说,JavaParser背后的人们应该像为其他基本体一样研究为String添加一个枚举。 工作代码:
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!
好吧,这很正常: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
(虽然我没编译上面的代码,以确保它的正确性)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.