2016-08-16 319 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