java - 如何将 Javassist CtClass 导出到文件

标签 java

我尝试使用 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

关于java - 如何将 Javassist CtClass 导出到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24703160/

相关文章:

java - 在 while 语句内使用嵌套的 if 和 else if 语句

java - 如何同步使用多线程?

java - 无法导入 java.util.function.*;

java - 代码在 Eclipse 中有效,但在命令行中无效

java - Pane 上的上下文菜单正确消失

java - PubNub hereNow 方法未返回预期的 uuids 列表

java - 正则表达式将以下行拆分为各个字段?

Java android 添加动态项目到菜单

java - 调用seam组件中的私有(private)方法

java - 如何剪切特定字符之前的所有内容