簡體   English   中英

如何將Javassist CtClass導出到文件

[英]how to export Javassist CtClass to file

我嘗試使用javassist CtClass將動態創建的類導出到文件。 我的代碼如下:

 public Class generate() throws NotFoundException,
        CannotCompileException {

    ClassPool pool = ClassPool.getDefault();
    CtClass targetClass =  pool.makeClass("ExampleController");

    // make class fields
    Iterator i = fields.iterator();
    while (i.hasNext()) {

        ClassFIeldProperty fieldProperty = (ClassFIeldProperty) i.next();
        CtClass fieldStoringType = pool.makeClass(fieldProperty.getStoringType().getName());
        Initializer fieldValue = CtField.Initializer.byNew(pool.makeClass(fieldStoringType.getName()));
        String fieldName = fieldProperty.getName();
        AnnotationsAttribute annotation = fieldProperty.getAnnotationAttribute();

        CtField field = new CtField(fieldStoringType, fieldName, targetClass);
        field.getFieldInfo().addAttribute(annotation);
        targetClass.addField(field,fieldValue);

    }

    // now we have class with some fields

    Class classWithFields = targetClass.toClass();

如何使用類定義將classWithFields導出並保存到文件(ExampleController.java)

   // code likes:
    File sourceFile = new File("/temp/ExampleController.java");
    try (FileWriter writer = new FileWriter(sourceFile)) {
        writer.write(classWithFields.toString());
    }

   // doesnt work - file not appear

嘗試使用以下代碼:

            DataOutputStream out = new DataOutputStream(new FileOutputStream("WelcomeController2.java"));
            targetClass.getClassFile().write(out);

並檢查目錄:

 C:\Users\UserAcccountName\AppData\Roaming\NetBeans\8.0\config\GF_4.0\domain1\config

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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