JDK8 字节码操作

2023-11-17

java字节码技术:

  1:BCEL  基于汇编

  2:ASM  轻量级

  3: javassist  性能比发射高, 比asm低, 使用简单

 4: cglib 基于ASM

 

 应用场景:

  1: 动态修改class文件, 对类进行增删改。

  2:aop技术

 3:lombok 去除重复代码

 

代码:

 1: pom 引入

        <dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.24.0-GA</version>
		</dependency>

 

2: 创建一个user类

 public class User {
	
	 private String name ;
	 private Integer age;
	 

}

 

3: 字节码操作

public class Test002 {

	public static void main(String[] args)throws Exception {
		 ClassPool pool = ClassPool.getDefault();
		 //获取要操作的类
		 CtClass ctClass = pool.get("com.tang.entity.User");
		 //创建方法 
		 /*
		  * ctClass.voidType: 方法返回值
		  * sum  :方法名
		  *  new CtClass[]: 参数个数与参数类型
		  *  ctClass:操作的类
		  */
		 CtMethod ctMethod =  new CtMethod(ctClass.voidType,"sum", new CtClass[] { ctClass.intType, ctClass.intType}, ctClass);
		//参数1和2 使用$符号区分
		 ctMethod.setBody("{System.out.println(\"sum:\"+($1+$2) );}");
		 
		 ctClass.addMethod(ctMethod);
           //写入硬盘
		 ctClass.writeFile("i:");
 }

}

 

4: 反编译 字节码文件: 使用 java decompiler

 

5: 使用反射动态调用创建的方法:

public class Test002 {

	public static void main(String[] args)throws Exception {
		 ClassPool pool = ClassPool.getDefault();
		 //获取要操作的类
		 CtClass ctClass = pool.get("com.tang.entity.User");
		 //创建方法 
		 /*
		  * ctClass.voidType: 方法返回值
		  * sum  :方法名
		  *  new CtClass[]: 参数个数与参数类型
		  *  ctClass:操作的类
		  */
		 CtMethod ctMethod =  new CtMethod(ctClass.voidType,"sum", new CtClass[] { ctClass.intType, ctClass.intType}, ctClass);
		//参数1和2 使用$符号区分
		 ctMethod.setBody("{System.out.println(\"sum:\"+($1+$2) );}");
		 
		 ctClass.addMethod(ctMethod);
		 ctClass.writeFile("i:");
		 
		 Class<?> user = ctClass.toClass();
		 Object newInstance = user.newInstance();
		 //反射调用方法执行
		 Method sumMethod = user.getDeclaredMethod("sum", int.class, int.class);
		 sumMethod.invoke(newInstance, 5, 2);
	}
}

 

效果:

 

 

 

 

 

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JDK8 字节码操作 的相关文章

  • Python实战

    逆向完美世界登录 js代码调试阶段 1 查看密码关键字段 2 Ctrl shift f全局搜索 password 找到相关js文件 3 从代码的setpublickey encrypt关键字可以看出 使用了非对称加密算法 4 此处打断点 再

随机推荐