簡體   English   中英

使用JavaParser將字符串字段添加到新的compilationUnit

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM