首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用compilationUnit向新的JavaParser添加字符串字段

使用compilationUnit向新的JavaParser添加字符串字段
EN

Stack Overflow用户
提问于 2016-08-16 09:18:01
回答 1查看 802关注 0票数 0

这也许是个愚蠢的问题,但我想说明主题是什么。我想在新的classOrInterfaceobject中向新声明的compilationUnit中添加一个新的字符串字段。但从源文件中我可以看出,这种选择是不可能的。primitiveClass只保存所有其他原语的枚举,长、字符、字节等。

我是不是遗漏了什么?还是开发人员忘记了字符串选项?

由于Riduidels的回答,解决了问题,我设法破解了代码,可以这么说:)问题是创建一个新的ClassOrInterfaceType,并将其命名为String,非常简单。虽然,我必须说,支持JavaParser的人应该考虑为字符串添加一个枚举,就像他们为其他Primitives添加的一样。工作代码:

代码语言:javascript
复制
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!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-16 09:28:04

这是非常正常的: JavaParser类型层次结构非常接近于Java源文件中的内容。在源文件中,您不直接将字符串放在文件中,而是放在文件中声明的类中。

这一点在JavaParser节从零开始创建CompilationUnit中有很好的描述,哪些内容可以被寻址成为

代码语言:javascript
复制
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的简单字段(尽管我没有编译上述代码以确保其正确性)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38971010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档