ASM创建java类

时间:2014-10-16 20:37:21

标签: java

我正在尝试使用ASM创建一个简单的类文件

我尝试过如下:

    ClassPrinter c = new ClassPrinter();
    ClassReader cr = new ClassReader(new FileInputStream("path/to/class"));
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS|ClassWriter.COMPUTE_FRAMES);
    cw.newClass("MyClass");
    cw.newField("owner", "value", "I");
    cr.accept(c, 0);
    for(String s : c.values){
        System.out.println(s);
    }
    ClassReader writerReader = new ClassReader(new FileInputStream("C:\\generated.class"));
    writerReader.accept(cw,0);

但是在创建ClassReader时会出现ArrayIndexOutOfBoundsException。

C:\ generated.class现在是一个空文件。

ClassPrinter是一个访问者,它只是遍历所有实体并使用system.out.println打印它们

如何做到这一点?

我需要能够从头创建类,而不仅仅是附加到已有的类。

依赖关系:

<dependency>
    <groupId>org.ow2.asm</groupId>
    <artifactId>asm</artifactId>
    <version>5.0.3</version>
</dependency>

1 个答案:

答案 0 :(得分:0)

你似乎永远不会写文件“C:\ generated.class”

什么是cr以及代码片段中的c是什么?

在打开阅读器之前,似乎缺少这样的东西:

String filename = "C:\\generated.class"; 

// Generate class

System.out.println("Generating MyClass");
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS|ClassWriter.COMPUTE_FRAMES);
cw.newClass("MyClass");
cw.newField("owner", "value", "I");

// Print generated class to STDIO to see that is generated as expected

System.out.println("Generated:");
ClassPrinter cp = new ClassPrinter();
cp.accept(cw, 0);

// Write the generated class to a file

System.out.println("Writing " + filename);
FileOutputStream os = new FileOutputStream(filename);
os.write(cw.toByteArray());
os.close();

// Read the file back

System.out.println("Reading " + filename);
ClassReader cr = new ClassReader(new FileInputStream("C:\\generated.class"));

// Print the class 

System.out.println("Read");
cr.accept(c, 0);
cr.accept(cw,0);