2016-08-16 323 views
0

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

回答

1

嗯,這很正常:JavaParser類型層次結構非常接近您在Java源文件中的結構。在源文件中,您不要將字符串直接放在文件中,而是放在文件中聲明的類中。

這是相當好於JavaParser類部分Creating a CompilationUnit from scratch,其內容可以addapted成爲

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; 
    } 
} 

描述,這將創建包含在名爲含有名爲GeneratedClass一個簡單場GeneratedClassjava.parser.test的類文件(雖然我沒有編譯上述代碼以確保其正確性)。

+0

如果你已經得到這個工作,請與我分享你的代碼。我感到非常失落。 – SwissArmyKnife

+0

更新了我的問題,你幾乎沒有錯,謝謝你一百萬,你救了我的一天! – SwissArmyKnife