這可能是一個愚蠢的問題,但我想實現主題狀態。我想添加一個新的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