CSDN博客

img oicqren

动态生成JAVA代码(一)

发表于2004/11/3 19:35:00  738人阅读

分类: 技术文章


BCEL即Bytecode Engineering Library,它是一个第三方的字节码生成库,能帮助我们在内存中直接生成Java字节码。BCEL是一个源代码开放的免费代码库(http://sourceforge.net/projects/bcel/),可以帮助我们分析、创建、处理二进制的Java字节码。本文将说明任何用BCEL来动态生成JAVA代码。

/*

 * 创建日期 2004-7-2

 * 创建人 HongSoft

 * 文件名 TestBCEL.java

 */

package com.hongsoft.test;

 

import java.io.*;

import java.util.Stack;

//从sourceforge.net/projects/bcel/下载BCEL代码库

import de.fub.bytecode.classfile.*;

import de.fub.bytecode.generic.*;

import de.fub.bytecode.Constants;

 

public class TestBCEL  extends ClassLoader {

    private Object o;

    public static void  main(String[] args) {

           new TestBCEL ();      

}

 

    public  TestBCEL ()

       {

                 

              // 声明类, Trouble_ticket是类名, 超类是java.lang.Object

               //ACC代表access, new String[]{}是它要实现的接口的数组

               //效果:public Trouble_ticket{}

              ClassGen classgen

                     = new ClassGen("Trouble_ticket", "java.lang.Object", "",           Constants.ACC_PUBLIC | Constants.ACC_SUPER,new String[]{});

       

                //常量池

ConstantPoolGen cp = classgen.getConstantPool();

    

                  //构造属性,效果: public String creater=””;

                 FieldGen fg=new FieldGen(Constants.ACC_PUBLIC, Type.STRING,               "creater",cp);

                  //加入field

                 classgen.addField(fg.getField());

      

                       // 构造函数                                          classgen.addEmptyConstructor(Constants.ACC_PUBLIC);

                       //Byte形式

                       byte[] data = classgen.getJavaClass().getBytes();

                       //生成类

                       Class c = defineClass(data, 0, data.length);

                       try {

                           o= c.newInstance();

                            //程序效果              

                         System.out.println(o.getClass().getName());

                         System.out.println(o.getClass().getField("creater").getName());                        

                         System.out.println(classgen.getFields().length);

                       } catch (IllegalAccessException e) {

                           throw new RuntimeException(e.getMessage());

                       } catch (Exception e) {

                           throw new RuntimeException(e.getMessage());

                       }

       }

   

}

程序运行结果如下:

Trouble_ticket

creater

1

阅读全文
0 0

相关文章推荐

img
取 消
img