0

这可能是一个愚蠢的问题,但我想了解主题所说的内容。我想在新的编译单元中向新声明的 classOrInterfaceobject 添加一个新的 String 字段。但是从我从源文件中可以看出,该选项是不可能的。PrimitiveClass 只保存所有其他原语的枚举,Long、char、bytes 等。

我错过了什么吗?还是开发人员忘记了 String 选项?

解决了感谢Riduidels 的回答,我设法破解了代码,可以这么说:) 事情是创建一个新的 ClassOrInterfaceType 并将其命名为 String,很简单。不过,我必须说,JavaParser 背后的人应该考虑为 String 添加一个枚举,就像他们为其他 Primitives 所做的那样。工作代码:

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

谢谢瑞杜德尔!

4

1 回答 1

1

嗯,这很正常: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(尽管我没有编译上述代码以确保其正确性)。

于 2016-08-16T09:28:04.577 回答