two common ways to implement Java dynamics are:
① Byte code operation
② Reflex
runtime manipulation of bytecode allows us to do the following:
① dynamic generation of new classes
② dynamically changing the structure of a class (adding, deleting, modifying new properties or methods)
Advantages:
Less overhead than reflection, high performance
Javassist performance above reflection, less than ASM
BCEL (Byte Code Engineering Library):
is a widely used framework for Java classworking, which allows you to drill down into JVM assembly language for the details of class operations. Bcel and Javassist have different methods of processing bytecode, bcel operations at the actual JVM instruction level (Bcel has rich JVM instruction-level support) and javassist is emphasizing the source-code level of work.
Asm:
is a lightweight Java bytecode manipulation framework that directly involves operations and directives to the bottom of the JVM.
CGLIB (Code Generation Library):
is a powerful, high-performance, high-quality code generation class library, based on ASM implementations.
Javassist
is an open source class library for parsing, editing, and creating Java bytecode. Performance is worse than ASM, similar to Cglib, but simple to use, many open source frameworks are in use.
Import the Javassist.jar package:
1 /**2 * 3 * Test using javassist to generate a new class4 *5 * @authorZhang Xiaodao6 *7 */8 Public classDemo01 {9 Public Static voidMain (string[] args)throwsException {Ten //get the default class pool OneClasspool pool =Classpool.getdefault (); A //classes that need to be created -Ctclass cc = Pool.makeclass ("Com.zzp.bean.Emp"); - the //Create an attribute, or assign a value to a property -Ctfield f1 = ctfield.make ("Private int empno", CC); -Ctfield F2 = ctfield.make ("Private String ename", CC); - Cc.addfield (F1); + Cc.addfield (F2); - + //Create a related method A //To Create a Set/get method atCtmethod.make ("public int getempno () {return empno;}", CC); -Ctmethod.make ("public void setempno (int empno) {this.empno = empno;}", CC); - -Ctmethod m1 = Ctmethod.make ("Public String Getename () {return ename;}", CC); -Ctmethod m2 = ctmethod.make ("public void Setename (String ename) {this.ename = ename;}", CC); - Cc.addmethod (M1); in Cc.addmethod (m2); - to //adding constructors +Ctconstructor constructor =NewCtconstructor (NewCtclass[]{ctclass.inttype,pool.get ("Java.lang.String") - },cc); the //the method body of the constructor is set, and method can be set *Constructor.setbody ("{this.empno=empno; This.ename=ename;} "); $ Cc.addconstructor (constructor);Panax Notoginseng - //build the class that is written above to the desktop theCc.writefile ("C:/desktop"); +System.out.println ("Generate class succeeded"); A } the}
Fifth Java byte code operation