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