这可能是一个愚蠢的问题,但我想实现主题状态。我想添加一个新的String字段到新的新compilationUnit中新声明的classOrInterface对象。但从我可以从源文件中得知,这个选项是不可能的。 primitiveClass只对所有其他原语,Long,char,bytes等保存枚举。使用JavaParser将字符串字段添加到新的compilationUnit
我错过了什么吗?或者让开发人员忘记了字符串选项?
解决 感谢Riduidels答案,我设法破解密码,可以这么说:)事情是创建一个新的ClassOrInterfaceType,把它串,够简单。虽然,我必须说,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!
如果你已经得到这个工作,请与我分享你的代码。我感到非常失落。 – SwissArmyKnife
更新了我的问题,你几乎没有错,谢谢你一百万,你救了我的一天! – SwissArmyKnife