当前位置:网站首页>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远程提交spark任务到yarn集群

Implementation of asynchronous FIFO

什么是物联网

outline和box-shadow实现外轮廓圆角高光效果

密码强度验证示例

System. Accessviolationexception: an attempt was made to read or write to protected memory. This usually indicates that other memory is corrupted

node学习

Solve the timeout of dbeaver SQL client connection Phoenix query

Pl/sql creates and executes ORALCE stored procedures and returns the result set

瀑布流布局
随机推荐
继承的实现过程及ES5和ES6实现的区别
Spark提交参数--files的使用
Idea护眼色设置
Use the command to check the WiFi connection password under win10 system
MeanShift聚类-01原理分析
Stored procedure bias of SQL to LINQ
了解一下new的过程发生了什么
基于OpenCV和YOLOv3的目标检测实例应用
瀑布流布局
HBCK fix problem
密码强度验证示例
Spark SQL空值Null,NaN判断和处理
C#,C/S升级更新
SQL Server forcibly disconnects
本地缓存--Ehcache
Promise对象与宏任务、微任务
Idea远程提交spark任务到yarn集群
Spark 内存管理机制 新版
Process control (Part 1)
ice 100G 网卡分片报文 hash 问题