Bcel is Bytecode Engineering Library, which is a third-party byte code generation library that can help us directly generate Java bytecodes directly in memory. BCEL is a source code open free code base (http://sourceforge.net/projects/bcel/), can help us analyze, create, and process binary Java bytecodes. This article will explain any BCEL to dynamically generate Java code.
/ *
* Create a date 2004-7-2
* Create a human hongsoft
* File name Testbcel.java
* /
Package com.hongsoft.test;
Import java.io. *;
Import java.util.stack;
// Download BCEL Code Base from SourceForge.Net/Projects/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 ()
{
// Declaration, Trouble_ticket is a class name, super class is java.lang.object
// ACC represents Access, new string [] {} is an array of interfaces it wants to implement
// Effect: public Trouble_ticket {}
Classgen Classgen
= New Classgen ("Trouble_ticket", "Java.lang.Object", "", constants.acc_public | constants.acc_super, new string [] {});
// constant pool
ConstantPoolgen CP = Classgen.getConstantPool ();
// Construct attribute, effect: public string creater = "";
Fieldgen FG = New Fieldgen (constants.acc_public, type.string, "creater", cp);
// Add Field
Classgen.addfield (fg.getfield ());
// Constructor Classgen.adDemptyConstructor (constants.acc_public);
// Byte form
BYTE [] DATA = Classgen.getjavaclass (). getBytes ();
// Generate a class
Class C = DefineClass (Data, 0, Data.Length);
Try {
o = c.newinstance ();
// program effect
System.out.println (O.GetClass (). Getname ());
System.out.println (O.GetClass (). Getfield ("create"). GetName ());
System.out.println (Classgen.Getfields (). Length);
} catch (IllegaCcessException E) {
Throw new runtimeException (E.GetMessage ());
} catch (exception e) {
Throw new runtimeException (E.getMessage ());
}
}
The procedure run is as follows:
Trouble_ticket
Creater
1