当前位置:网站首页>JVM dynamic bytecode technology details
JVM dynamic bytecode technology details
2022-07-25 15:20:00 【Literary youth learn programming】
1 Bytecode technology application scenario
AOP technology 、Lombok Remove duplicate code plug-ins 、 Dynamic modification class Documents, etc.
2 Byte technology advantages
Java Bytecode enhancement refers to Java After bytecode generation , Modify it , Enhance its function , This approach is equivalent to making changes to the application's binaries .Java Bytecode enhancement is mainly to reduce redundant code , Improve performance, etc .
The main steps to enhance bytecode are :
1、 Modify bytecode
Get the original bytecode in memory , And then through some tools ( Such as ASM,Javaasist) To modify its byte[] Array , Get a new one byte Array .
2、 Make the modified bytecode effective
There are two ways :
1) Customize ClassLoader To load the modified bytecode ;
2) Replace the original bytecode : stay JVM Load the user's Class when , Intercept , Return the modified bytecode ; Or at runtime , Use Instrumentation.redefineClasses Method to replace the original bytecode
3 Common bytecode manipulation class libraries
BCEL
Byte Code Engineering Library(BCEL), This is a Apache Software Foundation Of Jakarta Part of the project .BCEL yes Java classworking A widely used framework , It allows you to go deep jvm Assembly language for class library operation details .BCEL And javassist There are different ways to handle bytecode ,BCEL In practice jvm Operate at the command level (BCEL Rich in jvm Instruction set support ) and javassist The emphasis is on source level work .
ASM
It's a lightweight Java Bytecode manipulation framework , It is directly related to JVM The underlying operations and instructions
High performance , High-quality
CGLB
Generate class library , be based on ASM Realization
javassist
It's an open source analysis , Edit and create Java Bytecode class library . Performance comparison ASM Bad , Follow cglib almost , But it's easy to use . Many open source frameworks use it .
Javassist advantage
– Less overhead than reflection , High performance .
–javassist Performance higher than reflection , lower than ASM
Operating bytecode at runtime allows us to perform the following functions :
– Dynamic generation New classes
– Dynamically change the structure of a class ( add to / Delete / modify New properties / Method )
javassist The outermost layer of API and JAVA In the reflection package of API rather similar .
it The main from CtClass , CtMethod, , as well as CtField Several categories make up . To execute and JDK Reflection API in java.lang.Class,java.lang.reflect.Method,java.lang.reflect.Method .Field same operation .
Method of operation
– Modify the method body of the existing method ( Insert code into an existing method body )
– The new method Delete method
javassist The limitations of
JDK5.0 The new grammar doesn't support ( Including generics 、 enumeration ) , Annotation modification is not supported , But it can go through the bottom javassist Class to solve , Specific reference : javassist.bytecode.annotation
Initialization of arrays is not supported , Such as String[]{"1","2"} , Unless only the capacity of the array is 1
Internal and anonymous classes are not supported
I won't support it continue and break expression .
For inheritance , Some don't . for example
class A {}
class B extends A {}
class C extends B {}
4. Use Javassist Create a class
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<?> clazz = Class.forName("com.itmayiedu.Test0005");
Object newInstance = clazz.newInstance();
Method method = clazz.getDeclaredMethod("sum", int.class, int.class);
Object invoke = method.invoke(newInstance, 1, 1);
}
public void sum(int a, int b) {
System.out.println("sum:" + a + b);
}
public static void main(String[] args) throws CannotCompileException, NotFoundException, IOException {
ClassPool pool = ClassPool.getDefault();
// establish class file
CtClass userClass = pool.makeClass("com.itmayiedu.entity.User");
// establish id attribute
CtField idField = CtField.make("private Integer id;", userClass);
// establish name attribute
CtField nameField = CtField.make("private Integer name;", userClass);
// Add attribute
userClass.addField(idField);
// Add attribute
userClass.addField(nameField);
// Create method
CtMethod getIdMethod = CtMethod.make("public Integer getId() {return id;}", userClass);
// Create method
CtMethod setIdMethod = CtMethod.make("public void setId(Integer id) { this.id = id; }", userClass);
// Add method
userClass.addMethod(getIdMethod);
// Add method
userClass.addMethod(setIdMethod);
// Add constructors
CtConstructor ctConstructor = new CtConstructor(new CtClass[] { CtClass.intType, pool.get("java.lang.String") },
userClass);
// establish Body
ctConstructor.setBody(" {this.id = id;this.name = name;}");
userClass.addConstructor(ctConstructor);
userClass.writeFile("F:/test");// Write the constructed class to F:\test Under the table of contents
}
5. Use Javassist Modify a class
public static void main(String[] args)
throws NotFoundException, CannotCompileException, InstantiationException, IllegalAccessException,
NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, IOException {
ClassPool pool = ClassPool.getDefault();
// Need to load class information
CtClass userClass = pool.get("com.itmayiedu.User");
// Methods to be added
CtMethod m = new CtMethod(CtClass.intType, "add", new CtClass[] { CtClass.intType, CtClass.intType },
userClass);
// Method permissions
m.setModifiers(Modifier.PUBLIC);
// Method body content
m.setBody("{System.out.println(\"Test003\"); return $1+$2;}");
userClass.addMethod(m);
userClass.writeFile("F:/test");// Write the constructed class to F:\test Under the table of contents
// Use reflection technology to perform methods
Class clazz = userClass.toClass();
Object obj = clazz.newInstance(); // By calling User Parameter free constructor
Method method = clazz.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(obj, 200, 300);
System.out.println(result);
}
边栏推荐
猜你喜欢

ESXI6.7.0 升级到7.0U3f(2022年7月12 更新)

Spark SQL空值Null,NaN判断和处理

反射-笔记

Spark memory management mechanism new version

如何解决Visual Studio中scanf编译报错的问题

Solve the timeout of dbeaver SQL client connection Phoenix query

Leo-sam: tightly coupled laser inertial odometer with smoothing and mapping

MySql的安装配置超详细教程与简单的建库建表方法

spark分区算子partitionBy、coalesce、repartition

防抖(debounce)和节流(throttle)
随机推荐
Spark partition operators partitionby, coalesce, repartition
Solve the error caused by too large file when uploading file by asp.net
从 join on 和 where 执行顺序认识T-sql查询执行顺序
Scala111-map、flatten、flatMap
The implementation process of inheritance and the difference between Es5 and ES6 implementation
反射-笔记
树莓派入门:树莓派的初始设置
JVM-参数配置详解
ESXI6.7.0 升级到7.0U3f(2022年7月12 更新)
How spark gets columns in dataframe --column, $, column, apply
Boosting之GBDT源码分析
MySQL之事务与MVCC
Sublimetext-win10 cursor following problem
Spark judges that DF is empty
Browser workflow (Simplified)
记一次Yarn Required executor memeory is above the max threshold(8192MB) of this cluster!
异步fifo的实现
Spark SQL UDF function
vscode 插件篇收集
HBCK fix problem