当前位置:网站首页>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);
}
边栏推荐
- Idea remotely submits spark tasks to the yarn cluster
- 6线SPI传输模式探索
- Application of object detection based on OpenCV and yolov3
- Spark DF增加一列
- Remember that spark foreachpartition once led to oom
- Solve the error caused by too large file when uploading file by asp.net
- 简易轮播图和打地鼠
- Scala110-combineByKey
- 流程控制(上)
- 任务、微任务、队列和调度(动画展示每一步调用)
猜你喜欢

流程控制(上)

Solve the timeout of dbeaver SQL client connection Phoenix query

spark分区算子partitionBy、coalesce、repartition

Implementation of asynchronous FIFO

Idea护眼色设置

反射-笔记

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

Use the command to check the WiFi connection password under win10 system

Visual Studio 2022 查看类关系图

Gbdt source code analysis of boosting
随机推荐
TypeScript学习2——接口
Fast-lio: fast and robust laser inertial odometer based on tightly coupled IEKF
Spark 内存管理机制 新版
Scala110-combineByKey
Redis elimination strategy list
When using jetty to run items, an error is reported: form too large or form too many keys
How spark gets columns in dataframe --column, $, column, apply
Handle Oracle deadlock
防抖(debounce)和节流(throttle)
任务、微任务、队列和调度(动画展示每一步调用)
The implementation process of inheritance and the difference between Es5 and ES6 implementation
记一次redis超时
Cmake specify opencv version
Implementation of redis distributed lock
Spark sql 常用时间函数
SPI传输出现数据与时钟不匹配延后问题分析与解决
VS2010 add WAP mobile form template
Spark 判断DF为空
反射-笔记
vscode 插件篇收集