gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:38:52 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com