首页 文章 精选 留言 我的

精选列表

搜索[PWA技术],共10000篇文章
优秀的个人博客,低调大师

springboot如何用jar包启动,同时为不同机房设置不同的配置文件 | 京东云技术团队

1、首先先把配置文件从jar中抽离 示例代码: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.2.0</version> <configuration> <excludes> <exclude>**/spring-xxx.xml</exclude> </excludes> </configuration> </plugin> 2、把抽离的配置文件,放到conf目录下 利用maven-assembly-plugin,抽取配置文件到conf目录下, 示例代码: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.3.0</version> <configuration> <descriptors> <descriptor>src/main/assembly/assembly.xml</descriptor> </descriptors> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin>  assembly.xml内容如下: <assembly> <id>assembly</id> <formats> <format>zip</format> <format>dir</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <fileSets> <fileSet> <directory>${basedir}/src/bin</directory> <outputDirectory>bin</outputDirectory> <fileMode>0755</fileMode> </fileSet> </fileSets> <files> <file> <source>${project.build.directory}/${project.build.finalName}.jar</source> <outputDirectory>lib</outputDirectory> </file> <file> <source>${basedir}/../xxx/target/classes/spring/spring-xxx.xml</source> <outputDirectory>conf</outputDirectory> </file> <file> <source>${basedir}/../xxx/target/classes/spring/spring-xxx.xml</source> <outputDirectory>conf</outputDirectory> </file> </files> </assembly> 最终效果如下:  3、修改maven打包配置将conf加入到classpath中 示例代码如下: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.2.0</version> <configuration> <archive> <manifestEntries> <Class-Path>../conf/</Class-Path> </manifestEntries> </archive> </configuration> </plugin> 最终达到的效果是: 将springboot的jar包解压后,可以看到.MF文件中加了一个类路径 ../conf  特别注意: java -jar XX 使用-jar启动java进程的,-classpath不会生效了,如果要加类路径,只能通过改maven的打包参数,从而使得.MF文件加了Class-Path属性后,才可以!!!! 4、到部署平台上新建conf文件夹,将要覆盖的配置文件加入进去 这样,部署平台的配置就会覆盖maven打包出来的配置文件 5、测试是否生效 在部署平台上,将部署平台上的配置文件里的,rpc框架的服务别名设置为:xxx 代码里的服务别名是yyy,然后通过测试发现生效的别名是xxx。 因为,springboot启动后,使用的是conf下配置文件,然后conf下的配置文件会被部署平台上新建的配置文件覆盖, 这样为不同的机房新建不同的配置文件,这样也就实现了springboot的项目如何既要用jar包启动,同时还可以为不同的机房设置不同的配置文件 作者:京东科技李意文 来源:京东云开发者社区 转载请注明来源

优秀的个人博客,低调大师

Spring配置文件的魔法炼金术:如何制造容器化时代的完美配方 | 京东物流技术团队

前言 基于现代服务的云原生十二要素理论,我们在采用容器化部署时,要保证同一个镜像可以满足不同环境的部署要求,而不是不同环境打包不同的景象。本文档主要介绍一种基于spring框架的满足不同环境配置的编译打包方案,满足同一个镜像可以在环境分组下通过启动项配置实现不同环境的部署。 现有方案及问题 我们见过最常见的配置文件管理方案,是基于Maven的profile配置来实现多环境切换的,它的弊端在于,我们将profile配置在pom.xml中,每次编译打包时,需要通过编译指令-P来标识当前环境配置。这样导致的问题是,我们打包的镜像具有了环境属性,不符合一个镜像多环境部署的要求。 还有一种配置方案,就是基于Spring profile进行配置文件管理。针对这两种方案,我接下来会进行一些分析和对比。 两种profiles配置的不同和优劣对比 a. 两种profiles方案对比 1. Maven 的 profiles: ◦ Maven 的 profiles 是在构建时根据环境或其他条件激活不同的配置集合。可以在项目的pom.xml文件中定义多个 profile,并使用 Maven 命令行参数或其他配置来激活特定的 profile。 ◦ 优势: ▪ 灵活性高,可以根据不同的构建环境或条件激活不同的 profile。 ▪ 可以在构建过程中使用不同的依赖、插件配置等。 ◦ 劣势: ▪ 配置相对分散,需要在 Maven 的pom.xml文件中定义和管理多个 profile。 ▪ 配置与代码分离,不够直观。 2. Spring 的application.properties的 profile 配置: ◦ Spring 的application.properties文件可以根据激活的 profile 来加载不同的配置。可以在application.properties文件中定义多个 profile 下的配置,并使用配置文件或环境变量来激活特定的 profile。 ◦ 优势: ▪ 配置集中,可以在一个文件中定义多个 profile 下的配置,更易于管理和维护。 ▪ 配置与代码相近,更直观易读。 ◦ 劣势: ▪ 激活 profile 的方式相对有限,通常需要通过配置文件或环境变量来指定。 ▪ 不适用于构建过程中的配置,主要用于应用程序的运行配置。 总的来说,Maven profiles 更适用于构建过程中的配置,可以根据构建环境或条件激活不同的 profile,而 Spring 的application.properties的 profile 配置更适用于应用程序的运行配置,可以根据不同的 profile 加载不同的配置。具体选择哪种方式取决于你的需求和偏好。 b. 在云原生和容器化的部署场景分析 在云原生和容器化的部署场景下,我更倾向使用 Spring 的application.properties的 profile 配置方式。 以下是在云原生和容器化部署场景下,使用application.properties的 profile 配置方式的优势: 环境无关性:application.properties可以根据激活的 profile 加载不同的配置,使得应用程序在不同的环境中运行时具有一致的行为。这对于云原生和容器化的部署非常重要,因为应用程序可能需要在不同的环境(例如开发、测试、生产)中运行。 配置集中化:使用application.properties的 profile 配置方式,可以在一个文件中定义多个 profile 下的配置,使得配置管理更加集中和方便。这对于云原生和容器化的部署场景非常有帮助,因为可以根据不同的 profile 加载适当的配置,而无需分散地管理多个 Maven profiles。 容器友好性:在容器化的部署场景中,通常使用容器编排工具(如 Kubernetes)来管理应用程序的配置和部署。使用application.properties的 profile 配置方式,可以通过环境变量或配置文件中的属性来指定激活的 profile,从而实现与容器编排工具的集成。 综上所述,使用 Spring 的 application.properties 的 profile 配置方式更适合云原生和容器化的部署场景,因为它提供了环境无关性、配置集中化和容器友好性的优势。 基于properties的多环境配置方案实践 以下方案以springboot为例,当然springMVC方案也是可以适配,只是需要额外配置一下,介于我们新项目基本都是基于springboot搭建,此处不展开springMVC的实线方案,如有需要,我再额外提供mvc的配置方案。 a. 配置文件树  如上图所示 properties文件夹:我们在properties文件夹下,基于不同的环境,简历单独文件夹,比如dev,online, test, uat等,每个文件夹下存放当前环境的配置信息。 spring文件夹: 下存放xml配置信息,比如常见的JSF配置(jsf.xml),以及其他需要通过xml配置注入的业务场景。当然基于springboot官网建议,大家尽量用注解代码方式实现bean注入,尽量减少xml的方式。 application.properties文件: 该文件里通过核心的配置spring.profiles.active=**来标识当前是哪个profile环境。当然一些其他全局类配置也可以放在此处。需要注意application.properties文件需要配置在行云部署中分组配置里,因为此文件需要基于不同的部署分组进行文件覆盖,以改变spring.profiles.active的值,如下图所示。当然,也可以通过运行时启动指令,进行不同的profile选择。 important.properties文件: 该文件为京东行云部署规约,把秘钥等安全性高的文件以加密存储的方式存放在该文件中,并部署到行云部署分组的远程配置里。 具体行云部署里的配置如下:  b. properties文件加载 正常情况下,properties/**/*.properties下的配置文件是不会自动加载到启动项里的。所以需要通过额外的方式动态加载,具体方法是通过spring框架下的PropertySourcesPlaceholderConfigurer的类属性,结合环境变量,动态批量加载配置文件。(额外说明,如果是springMVC框架,也可以通过xml配置context:property-placeholder属性来实现。) 具体代码如下: /** * 配置文件环境配置 * * @Author zhaoyongping * @date 2023/7/10 15:13 * @ClassName EnvPropertiesConfig * @Descripiton 配置文件环境配置 **/ @Configuration public class EnvPropertiesConfig { /** * 加载属性配置 * * @param environment 环境属性 * @return PropertySourcesPlaceholderConfigurer * @author zhaoyongping * @date 2023/7/10 15:13 * @description 加载属性配置 */ @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfig(Environment environment) throws IOException { PropertySourcesPlaceholderConfigurer config = new PropertySourcesPlaceholderConfigurer(); String[] activeProfiles = environment.getActiveProfiles(); if (activeProfiles.length > 0) { String resourceUrl = "classpath:properties/" + environment.getActiveProfiles()[0] + "/*.properties"; config.setLocations( new PathMatchingResourcePatternResolver().getResources(resourceUrl)); } else { //兜底策略 config.setLocations( new PathMatchingResourcePatternResolver() .getResources("classpath:properties/dev/*.properties")); } return config; } } 总结 通过以上步骤,我们可以实现编译打包镜像不需要跟环境变量绑定,而只需要在启动运行时基于不同的分组动态配置的applicaiton.properties文件,来实现不同环境的适配。这种可以在运行时变更配置文件的机制,更适合在云原生时代下的容器化部署方案,也利于我们的服务的可移植性。当然,以上只是笔者个人的一个实践经验,并不能代表它是最优实践方案。 作者:京东物流 赵勇萍 来源:京东云开发者社区 自猿其说Tech 转载请注明来源

优秀的个人博客,低调大师

ASM字节码操作类库(打开java语言世界通往字节码世界的大门) | 京东云技术团队

前言:授人以鱼不如授人以渔,应用asm的文章有很多,简单demo的也很多,那么ASM都具备哪些能力呢?如何去学习编写ASM代码呢?什么样的情景需要用到ASM呢?让我们带着这些问题阅读这篇文章吧。 这里由于篇幅限制做了删减(第六部分TreeApi和CoreApi的比较、核心API类的介绍等),如果有兴趣可以联系作者进行交流, 个人认为核心在于第五部分如何查看一个想写的类的ASM代码如何写,以及全面了解ASM都有哪些能力,这样在后面的特定场景下我们才会知道可以通过它来实现想做的功能 一、ASM介绍 1、ASM 是什么 ASM是一个通用的Java字节码操作和分析框架。它可以用于修改现有类或直接以二进制形式动态生成类。ASM提供了一些常见的字节码转换和分析算法,可以从中构建定制的复杂转换和代码分析工具。ASM提供了与其他Java字节码框架类似的功能,但侧重于性能。由于它的设计和实现尽可能小和快,因此非常适合在动态系统中使用(但当然也可以以静态方式使用,例如在编译器中)。 一个.java文件经过Java编译器(javac)编译之后会生成一个.class文件。在.class文件中,存储的是字节码(ByteCode)数据。ASM所操作的对象是字节码(ByteCode),而在许多情况下,字节码(ByteCode)的具体表现形式是.class文件。 ASM处理字节码(ByteCode)的方式是“拆分-修改-合并”。 字节码工具 类创建 实现接口 方法调用 类扩展 父类方法调用 优点 缺点 常见使用 学习成本 java-proxy 支持 支持 支持 不支持 不支持 简单动态代理首选 功能有限,不支持扩展 spring-aop,MyBatis 1星 asm 支持 支持 支持 支持 支持 任意字节码插入,几乎不受限制 学习难度大,编写代码多 cglib 5星 javaassit 支持 支持 支持 支持 支持 java原始语法,字符串形式插入,写入直观 不支持jdk1.5以上的语法,如泛型,增强for Fastjson,MyBatis 2星 cglib 支持 支持 支持 支持 支持 与bytebuddy看起来差不多 正在被bytebuddy淘汰 EasyMock,jackson-databind 3星 bytebuddy 支持 支持 支持 支持 支持 支持任意维度的拦截,可以获取原始类、方法,以及代理类和全部参数 不太直观,学习理解有些成本,API非常多 SkyWalking,Mockito,Hibernate,powermock 3星 比较表格参考: http://xingyun.jd.com/shendeng/article/detail/7826 ASM官网:https://asm.ow2.io/ ASM源码:https://gitlab.ow2.org/asm/asm 开发者指南:https://asm.ow2.io/developer-guide.html 2、ASM能做什么 生成、修改、删除(接口、类、字段、方法...)ASM能够对字节码数据进行analyze、generate、transformation,ASM可以形象的理解为“Java语言世界”边缘上一扇大门,通过这扇大门,可以帮助我们进入到“字节码的世界”。 3、ASM实际的使用场景 3.1、Spring当中的ASM 第一个应用场景,是Spring框架当中的AOP。 在很多Java项目中,都会使用到Spring框架,而Spring框架当中的AOP(Aspect Oriented Programming)是依赖于ASM的。具体来说,Spring的AOP,可以通过JDK的动态代理来实现,也可以通过CGLIB实现。其中,CGLib (Code Generation Library)是在ASM的基础上构建起来的,所以,Spring AOP是间接的使用了ASM。(参考自 Spring Framework Reference Documentation的 8.6 Proxying mechanisms)。 3.2、JDK当中的ASM 第二个应用场景,是JDK当中的Lambda表达式。 在Java 8中引入了一个非常重要的特性,就是支持Lambda表达式。Lambda表达式,允许把方法作为参数进行传递,它能够使代码变的更加简洁紧凑。但是,我们可能没有注意到,其实,在现阶段(Java 8版本),Lambda表达式的调用是通过ASM来实现的。 在rt.jar文件的jdk.internal.org.objectweb.asm包当中,就包含了JDK内置的ASM代码。在JDK 8版本当中,它所使用的ASM 5.0版本。 如果我们跟踪Lambda表达式的编码实现,就会找到InnerClassLambdaMetafactory.spinInnerClass()方法。在这个方法当中,我们就会看到:JDK会使用jdk.internal.org.objectweb.asm.ClassWriter来生成一个类,将lambda表达式的代码包装起来。 LambdaMetafactory.metafactory() 第一步,找到这个方法​ InnerClassLambdaMetafactory.buildCallSite() 第二步,找到这个方法 ​ InnerClassLambdaMetafactory.spinInnerClass() 第三步,找到这个方法 4、 ASM的两个组成部分 从组成结构上来说,ASM分成两部分,一部分为Core API,另一部分为Tree API。 其中,Core API包括asm.jar、asm-util.jar和asm-commons.jar;其中,Tree API包括asm-tree.jar和asm-analysis.jar。 asm.jar内核心类:ClassReader、ClassVisitor、ClassWriter、FieldVisitor、FieldWriter、MethodVisitor、MethodWriter、Label、Opcodes、Type ClassReader类,负责读取.class文件里的内容,然后拆分成各个不同的部分。ClassVisitor类,负责对.class文件中某一部分里的信息进行修改。ClassWriter类,负责将各个不同的部分重新组合成一个完整的.class文件。 asm-util.jar内核心类 以Check开头的类,主要负责检查(Check)生成的.class文件内容是否正确。以Trace开头的类,主要负责将.class文件的内容打印成文字输出。根据输出的文字信息,可以探索或追踪(Trace).class文件的内部信息。 5、ClassFile 我们都知道,在.class文件中,存储的是ByteCode数据。但是,这些ByteCode数据并不是杂乱无章的,而是遵循一定的数据结构。 这个.class文件遵循的数据结构就是由 Java Virtual Machine Specification中定义的 The class File Format 6、常见的字节码类库 Apache Commons BCEL:其中BCEL为Byte Code Engineering Library首字母的缩写。 Javassist:Javassist表示Java programming assistant ObjectWeb ASM:本课程的研究对象。 Byte Buddy:在ASM基础上实现的一个类库。 二、无中生有 1、生成新的接口 预期目标: 生成一个正常接口结构定义的.class文件 public interface ASMInterface { byte byteType = 1; short shortType = 1; int intType = 1; char charType = 's'; float floatType = 1.1F; double doubleType = 1.2; long longType = 1L; boolean booleanType = false; Byte ByteType = 1; Short ShortType = Short.valueOf((short)1); Integer IntegerType = 1; String StringType = "s"; Float FloatType = 1.1F; Double DoubleType = 1.1; Long LongType = 1L; Boolean BooleanType = true; void function(); default String defaultFunction(Integer integer) { System.out.println("param = " + integer); return String.valueOf(integer); } static Integer getInteger(String str) { return Integer.valueOf(str); } } 编码实现: public class InterfaceGenerateCore { public static void main(String[] args) throws Exception { String relative_path = "sample/ASMGenerateInterface.class"; String filepath = FileUtils.getFilePath(relative_path); // (1) 生成byte[]内容 byte[] bytes = dump(); // (2) 保存byte[]到文件 FileUtils.writeBytes(filepath, bytes); } public static byte[] dump() throws Exception { // (1) 创建ClassWriter对象 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); // (2) 调用visitXxx()方法,调用顺序和说明如下 /* * visit * [visitSource][visitModule][visitNestHost][visitPermittedSubclass][visitOuterClass] * (visitAnnotation | * visitTypeAnnotation | * visitAttribute)* * (visitNestMember | * visitInnerClass | * visitRecordComponent | * visitField | * visitMethod)* * visitEnd * []: 表示最多调用一次,可以不调用,但最多调用一次。 * ()和|: 表示在多个方法之间,可以选择任意一个,并且多个方法之间不分前后顺序。 * *: 表示方法可以调用0次或多次。 * */ //定义接口 /* *visit(version, access, name, signature, superName, interfaces) *version: 表示当前类的版本信息。在下述示例代码中,其取值为Opcodes.V1_8,表示使用Java 8版本。 *access: 表示当前类的访问标识(access flag)信息。在下面的示例中,access的取值是ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE,也可以写成ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE。如果想进一步了解这些标识的含义,可以参考Java Virtual Machine Specification的Chapter 4. The class File Format部分。 *name: 表示当前类的名字,它采用的格式是Internal Name的形式。在.java文件中,我们使用Java语言来编写代码,使用类名的形式是Fully Qualified Class Name,例如java.lang.String;将.java文件编译之后,就会生成.class文件;在.class文件中,类名的形式会发生变化,称之为Internal Name,例如java/lang/String。因此,将Fully Qualified Class Name转换成Internal Name的方式就是,将.字符转换成/字符。 *signature: 表示当前类的泛型信息。因为在这个接口当中不包含任何的泛型信息,因此它的值为null。 *superName: 表示当前类的父类信息,它采用的格式是Internal Name的形式。 *interfaces: 表示当前类实现了哪些接口信息。 **/ cw.visit( V1_8, // version ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, // access "sample/ASMGenerateInterface", // name null, // signature "java/lang/Object", // superName null // interfaces ); //定义字段-基本类型 /* * visitField(access, name, descriptor, signature, value) *access参数:表示当前字段或方法带有的访问标识(access flag)信息,例如ACC_PUBLIC、ACC_STATIC和ACC_FINAL等。 *name参数:表示当前字段或方法的名字。 *descriptor参数:表示当前字段或方法的描述符。这些描述符,与我们平时使用的Java类型是有区别的。byte-B、short-S、int-I、char-C、具体可以参考如下示例代码 *signature参数:表示当前字段或方法是否带有泛型信息。换句话说,如果不带有泛型信息,提供一个null就可以了;如果带有泛型信息,就需要给它提供某一个具体的值。 *value参数:是visitField()方法的第5个参数。这个参数的取值,与当前字段是否为常量有关系。如果当前字段是一个常量,就需要给value参数提供某一个具体的值;如果当前字段不是常量,那么使用null就可以了。 * */ { FieldVisitor fv1 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "byteType", "B", null, new Integer(1)); fv1.visitEnd(); } { FieldVisitor fv2 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "shortType", "S", null, new Integer(1)); fv2.visitEnd(); } { FieldVisitor fv3 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "intType", "I", null, new Integer(1)); fv3.visitEnd(); } { FieldVisitor fv4 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "charType", "C", null, 's'); fv4.visitEnd(); } { FieldVisitor fv5 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "floatType", "F", null, new Float("1.1")); fv5.visitEnd(); } { FieldVisitor fv6 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "doubleType", "D", null, new Double("1.2")); fv6.visitEnd(); } { FieldVisitor fv7 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "longType", "J", null, new Long(1L)); fv7.visitEnd(); } { FieldVisitor fv8 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "booleanType", "Z", null, new Integer(0)); fv8.visitEnd(); } //定义变量-包装类型 { FieldVisitor fv11 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "ByteType", "Ljava/lang/Byte;", null, null); fv11.visitEnd(); } { FieldVisitor fv12 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "ShortType", "Ljava/lang/Short;", null,null); fv12.visitEnd(); } { FieldVisitor fv13 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "IntegerType", "Ljava/lang/Integer;", null,null); fv13.visitEnd(); } { FieldVisitor fv14 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "StringType", "Ljava/lang/String;", null, "s"); fv14.visitEnd(); } { FieldVisitor fv15 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "FloatType", "Ljava/lang/Float;", null,null); fv15.visitEnd(); } { FieldVisitor fv16 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "DoubleType", "Ljava/lang/Double;", null,null); fv16.visitEnd(); } { FieldVisitor fv17 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "LongType", "Ljava/lang/Long;", null, null); fv17.visitEnd(); } { FieldVisitor fv18 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, "BooleanType", "Ljava/lang/Boolean;", null, null); fv18.visitEnd(); } //定义方法-抽象方法 /* * visitMethod(access, name, descriptor, signature, exceptions) *access参数:表示当前字段或方法带有的访问标识(access flag)信息,例如ACC_PUBLIC、ACC_STATIC和ACC_FINAL等。 *name参数:表示当前字段或方法的名字。 *descriptor参数:表示当前字段或方法的描述符。这些描述符,与我们平时使用的Java类型是有区别的。()内为入参,后面为反参 *signature参数:表示当前字段或方法是否带有泛型信息。换句话说,如果不带有泛型信息,提供一个null就可以了;如果带有泛型信息,就需要给它提供某一个具体的值。 *exceptions参数:是visitMethod()方法的第5个参数。这个参数的取值,与当前方法声明中是否具有throws XxxException相关。 * */ { MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "function", "()V", null, null); mv1.visitEnd(); } //定义方法-默认方法 { MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "defaultFunction", "(Ljava/lang/Integer;)Ljava/lang/String;", null, null); mv2.visitCode(); mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv2.visitTypeInsn(NEW, "java/lang/StringBuilder"); mv2.visitInsn(DUP); mv2.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false); mv2.visitLdcInsn("param = "); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false); mv2.visitVarInsn(ALOAD, 1); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", false); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mv2.visitVarInsn(ALOAD, 1); mv2.visitMethodInsn(INVOKESTATIC, "java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;", false); mv2.visitInsn(ARETURN); mv2.visitMaxs(3, 2); mv2.visitEnd(); } //定义方法-静态方法 { MethodVisitor mv3 = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "getInteger", "(Ljava/lang/String;)Ljava/lang/Integer;", null, null); mv3.visitCode(); mv3.visitVarInsn(ALOAD, 0); mv3.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(Ljava/lang/String;)Ljava/lang/Integer;", false); mv3.visitInsn(ARETURN); mv3.visitMaxs(1, 1); mv3.visitEnd(); } { MethodVisitor mv4 = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null); mv4.visitCode(); mv4.visitInsn(ICONST_1); mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false); mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "ByteType", "Ljava/lang/Byte;"); mv4.visitInsn(ICONST_1); mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false); mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "ShortType", "Ljava/lang/Short;"); mv4.visitInsn(ICONST_1); mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false); mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "IntegerType", "Ljava/lang/Integer;"); mv4.visitLdcInsn(new Float("1.1")); mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false); mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "FloatType", "Ljava/lang/Float;"); mv4.visitLdcInsn(new Double("1.1")); mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false); mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "DoubleType", "Ljava/lang/Double;"); mv4.visitInsn(LCONST_1); mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false); mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "LongType", "Ljava/lang/Long;"); mv4.visitInsn(ICONST_1); mv4.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); mv4.visitFieldInsn(PUTSTATIC, "sample/ASMInterface", "BooleanType", "Ljava/lang/Boolean;"); mv4.visitInsn(RETURN); mv4.visitMaxs(2, 0); mv4.visitEnd(); } cw.visitEnd(); // 注意,最后要调用visitEnd()方法 // (3) 调用toByteArray()方法 return cw.toByteArray(); } } 验证结果: 生成的接口是否正确 public class HelloWorldRun { public static void main(String[] args) throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class<?> clazz = classLoader.loadClass("sample.ASMGenerateInterface"); Field[] declaredFields = clazz.getDeclaredFields(); if (declaredFields.length > 0) { System.out.println("fields:"); for (Field f : declaredFields) { Object value = f.get(null); System.out.println(" " + f.getName() + ": " + value); } } Method[] declaredMethods = clazz.getDeclaredMethods(); if (declaredMethods.length > 0) { System.out.println("methods:"); for (Method m : declaredMethods) { System.out.println(" " + m.getName()); } } } } 效果图如下:  2、生成新的类 预期目标: 生成一个正常类结构定义的.class文件 public class ASMClass { //定义变量-基本类型 byte byteType = 1; short shortType = 1; int intType = 1; char charType = 's'; float floatType = 1.1f; double doubleType = 1.2; long longType = 1; boolean booleanType = false; //定义变量-包装类型 Byte ByteType = 1; Short ShortType = 1; Integer IntegerType = 1; String StringType = "string"; Float FloatType = 1.1f; Double DoubleType = 1.1; Long LongType = 1l; @Deprecated Boolean BooleanType = true; /* * 静态方法 * */ public static Integer getInteger(String str) { return Integer.valueOf(str); } /* * 实例方法 * */ public String instanceMethod(Integer integer) { return String.valueOf(integer); } } 编码实现: public class ClassGenerateCore { public static void main(String[] args) throws Exception { String relative_path = "sample/ASMGenerateClass.class"; String filepath = FileUtils.getFilePath(relative_path); // (1) 生成byte[]内容 byte[] bytes = dump(); // (2) 保存byte[]到文件 FileUtils.writeBytes(filepath, bytes); } public static byte[] dump() throws Exception { // (1) 创建ClassWriter对象 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); // (2) 调用visitXxx()方法,调用顺序和说明如下 /* * visit * [visitSource][visitModule][visitNestHost][visitPermittedSubclass][visitOuterClass] * (visitAnnotation | * visitTypeAnnotation | * visitAttribute)* * (visitNestMember | * visitInnerClass | * visitRecordComponent | * visitField | * visitMethod)* * visitEnd * []: 表示最多调用一次,可以不调用,但最多调用一次。 * ()和|: 表示在多个方法之间,可以选择任意一个,并且多个方法之间不分前后顺序。 * *: 表示方法可以调用0次或多次。 * */ //定义接口 /* *visit(version, access, name, signature, superName, interfaces) *version: 表示当前类的版本信息。在下述示例代码中,其取值为Opcodes.V1_8,表示使用Java 8版本。 *access: 表示当前类的访问标识(access flag)信息。在下面的示例中,access的取值是ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE,也可以写成ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE。如果想进一步了解这些标识的含义,可以参考Java Virtual Machine Specification的Chapter 4. The class File Format部分。 *name: 表示当前类的名字,它采用的格式是Internal Name的形式。在.java文件中,我们使用Java语言来编写代码,使用类名的形式是Fully Qualified Class Name,例如java.lang.String;将.java文件编译之后,就会生成.class文件;在.class文件中,类名的形式会发生变化,称之为Internal Name,例如java/lang/String。因此,将Fully Qualified Class Name转换成Internal Name的方式就是,将.字符转换成/字符。 *signature: 表示当前类的泛型信息。因为在这个接口当中不包含任何的泛型信息,因此它的值为null。 *superName: 表示当前类的父类信息,它采用的格式是Internal Name的形式。 *interfaces: 表示当前类实现了哪些接口信息。 **/ cw.visit( V1_8, // version ACC_PUBLIC + ACC_SUPER, // access "sample/ASMGenerateClass", // name null, // signature "java/lang/Object", // superName null // interfaces ); //定义字段-基本类型 /* * visitField(access, name, descriptor, signature, value) *access参数:表示当前字段或方法带有的访问标识(access flag)信息,例如ACC_PUBLIC、ACC_STATIC和ACC_FINAL等。 *name参数:表示当前字段或方法的名字。 *descriptor参数:表示当前字段或方法的描述符。这些描述符,与我们平时使用的Java类型是有区别的。byte-B、short-S、int-I、char-C、具体可以参考如下示例代码 *signature参数:表示当前字段或方法是否带有泛型信息。换句话说,如果不带有泛型信息,提供一个null就可以了;如果带有泛型信息,就需要给它提供某一个具体的值。 *value参数:是visitField()方法的第5个参数。这个参数的取值,与当前字段是否为常量有关系。如果当前字段是一个常量,就需要给value参数提供某一个具体的值;如果当前字段不是常量,那么使用null就可以了。 * */ { FieldVisitor fv1 = cw.visitField(0, "byteType", "B", null, new Byte("1")); fv1.visitEnd(); } { FieldVisitor fv2 = cw.visitField(0, "shortType", "S", null, new Short("1")); fv2.visitEnd(); } { FieldVisitor fv3 = cw.visitField(0, "intType", "I", null, new Integer(1)); fv3.visitEnd(); } { FieldVisitor fv4 = cw.visitField(0, "charType", "C", null, "s"); fv4.visitEnd(); } { FieldVisitor fv5 = cw.visitField(0, "floatType", "F", null, new Float("1.1")); fv5.visitEnd(); } { FieldVisitor fv6 = cw.visitField(0, "doubleType", "D", null, new Double("1.2")); fv6.visitEnd(); } { FieldVisitor fv7 = cw.visitField(0, "longType", "J", null, new Long(1)); fv7.visitEnd(); } { FieldVisitor fv8 = cw.visitField(0, "booleanType", "Z", null, false); fv8.visitEnd(); } //定义变量-包装类型 { FieldVisitor fv11 = cw.visitField(0, "ByteType", "Ljava/lang/Byte;", null, 1); fv11.visitEnd(); } { FieldVisitor fv12 = cw.visitField(0, "ShortType", "Ljava/lang/Short;", null, 1); fv12.visitEnd(); } { FieldVisitor fv13 = cw.visitField(0, "IntegerType", "Ljava/lang/Integer;", null, 1); fv13.visitEnd(); } { FieldVisitor fv14 = cw.visitField(0, "StringType", "Ljava/lang/String;", null, "s"); fv14.visitEnd(); } { FieldVisitor fv15 = cw.visitField(0, "FloatType", "Ljava/lang/Float;", null, 1.1f); fv15.visitEnd(); } { FieldVisitor fv16 = cw.visitField(ACC_PUBLIC, "DoubleType", "Ljava/lang/Double;", null, 1.1); fv16.visitEnd(); } { FieldVisitor fv17 = cw.visitField(0, "LongType", "Ljava/lang/Long;", null, 1l); fv17.visitEnd(); } { FieldVisitor fv18 = cw.visitField(ACC_DEPRECATED, "BooleanType", "Ljava/lang/Boolean;", null, true); { AnnotationVisitor annotationVisitor0 = fv18.visitAnnotation("Ljava/lang/Deprecated;", true); annotationVisitor0.visitEnd(); } fv18.visitEnd(); } /* * visitMethod(access, name, descriptor, signature, exceptions) *access参数:表示当前字段或方法带有的访问标识(access flag)信息,例如ACC_PUBLIC、ACC_STATIC和ACC_FINAL等。 *name参数:表示当前字段或方法的名字。 *descriptor参数:表示当前字段或方法的描述符。这些描述符,与我们平时使用的Java类型是有区别的。()内为入参,后面为反参 *signature参数:表示当前字段或方法是否带有泛型信息。换句话说,如果不带有泛型信息,提供一个null就可以了;如果带有泛型信息,就需要给它提供某一个具体的值。 *exceptions参数:是visitMethod()方法的第5个参数。这个参数的取值,与当前方法声明中是否具有throws XxxException相关。 * */ //定义方法-静态代码块 { MethodVisitor mv2 = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null); mv2.visitCode(); mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv2.visitLdcInsn("class initialization method"); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mv2.visitInsn(RETURN); mv2.visitMaxs(2, 0); mv2.visitEnd(); } //定义方法-无参构造器 { MethodVisitor methodVisitor = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); methodVisitor.visitCode(); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(ICONST_1); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "byteType", "B"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(ICONST_1); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "shortType", "S"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(ICONST_1); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "intType", "I"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitIntInsn(BIPUSH, 115); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "charType", "C"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitLdcInsn(new Float("1.1")); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "floatType", "F"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitLdcInsn(new Double("1.2")); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "doubleType", "D"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(LCONST_1); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "longType", "J"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(ICONST_0); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "booleanType", "Z"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(ICONST_1); methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "ByteType", "Ljava/lang/Byte;"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(ICONST_1); methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "ShortType", "Ljava/lang/Short;"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(ICONST_1); methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "IntegerType", "Ljava/lang/Integer;"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitLdcInsn("string"); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "StringType", "Ljava/lang/String;"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitLdcInsn(new Float("1.1")); methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "FloatType", "Ljava/lang/Float;"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitLdcInsn(new Double("1.1")); methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "DoubleType", "Ljava/lang/Double;"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(LCONST_1); methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "LongType", "Ljava/lang/Long;"); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(ICONST_1); methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); methodVisitor.visitFieldInsn(PUTFIELD, "sample/ASMGenerateClass", "BooleanType", "Ljava/lang/Boolean;"); methodVisitor.visitInsn(RETURN); methodVisitor.visitMaxs(3, 1); methodVisitor.visitEnd(); } //定义方法-静态方法 { MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "getInteger", "(Ljava/lang/String;)Ljava/lang/Integer;", null, null); mv1.visitCode(); mv1.visitVarInsn(ALOAD, 0); mv1.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(Ljava/lang/String;)Ljava/lang/Integer;", false); mv1.visitInsn(ARETURN); mv1.visitMaxs(1, 1); mv1.visitEnd(); } //定义方法-实例方法 { MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "instanceMethod", "(Ljava/lang/Integer;)Ljava/lang/String;", null, null); mv2.visitCode(); mv2.visitVarInsn(ALOAD, 1); mv2.visitMethodInsn(INVOKESTATIC, "java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;", false); mv2.visitInsn(ARETURN); mv2.visitMaxs(1, 2); mv2.visitEnd(); } cw.visitEnd(); // 注意,最后要调用visitEnd()方法 // (3) 调用toByteArray()方法 return cw.toByteArray(); } } 验证结果: public class HelloWorldRun { public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("sample.ASMGenerateClass"); Method method = clazz.getDeclaredMethod("instanceMethod",Integer.class); Object instance = clazz.newInstance(); Object invoke = method.invoke(instance, new Integer(12)); Class<?> aClass = invoke.getClass(); System.out.println("aClass = " + aClass); } } 或者 public class HelloWorldRun { public static void main(String[] args) throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class<?> clazz = classLoader.loadClass("sample.ASMGenerateClass"); Field[] declaredFields = clazz.getDeclaredFields(); if (declaredFields.length > 0) { for (Field f : declaredFields) { Object value = f.get(null); System.out.println(" " + f.getName() + ": " + value); } } Method[] declaredMethods = clazz.getDeclaredMethods(); if (declaredMethods.length > 0) { for (Method m : declaredMethods) { System.out.println(" " + m.getName()); } } } } 效果图如下: ClassVisitor中visitXxx()的调用顺序 visit [visitSource][visitModule][visitNestHost][visitPermittedSubclass][visitOuterClass] ( visitAnnotation | visitTypeAnnotation | visitAttribute )* ( visitNestMember | visitInnerClass | visitRecordComponent | visitField | visitMethod )* visitEnd 其中,涉及到一些符号,它们的含义如下: []: 表示最多调用一次,可以不调用,但最多调用一次。 ()和|: 表示在多个方法之间,可以选择任意一个,并且多个方法之间不分前后顺序。 *: 表示方法可以调用0次或多次。 FieldVisitor中visitXxx()的调用顺序 ( visitAnnotation | visitTypeAnnotation | visitAttribute )* visitEnd MethodVisitor中visitXxx()的调用顺序 (visitParameter)* [visitAnnotationDefault] (visitAnnotation | visitAnnotableParameterCount | visitParameterAnnotation | visitTypeAnnotation | visitAttribute)* [ visitCode ( visitFrame | visitXxxInsn | visitLabel | visitInsnAnnotation | visitTryCatchBlock | visitTryCatchAnnotation | visitLocalVariable | visitLocalVariableAnnotation | visitLineNumber )* visitMaxs ] visitEnd 第一组,在visitCode()方法之前的方法。这一组的方法,主要负责parameter、annotation和attributes等内容 第二组,在visitCode()方法和visitMaxs()方法之间的方法。这一组的方法,主要负责当前方法的“方法体”内的opcode内容。其中,visitCode()方法,标志着方法体的开始,而visitMaxs()方法,标志着方法体的结束。 第三组,是visitEnd()方法。这个visitEnd()方法,是最后一个进行调用的方法。 不同的MethodVisitor对象,它们的visitXxx()方法是彼此独立的,只要各自遵循方法的调用顺序,就能够得到正确的结果。 三、狸猫换太子 1、修改类的版本 ClassVisitor子类实现 public class ClassChangeVersionVisitor extends ClassVisitor { public ClassChangeVersionVisitor(int api, ClassVisitor classVisitor) { super(api, classVisitor); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(Opcodes.V1_7, access, name, signature, superName, interfaces); } } 使用ClassVisitor的子类ClassChangeVersionVisitor进行类的版本修改 public class ASMModifyClass { public static void main(String[] args) throws Exception { String relative_path = "sample/HelloWorld.class"; String filepath = FileUtils.getFilePath(relative_path); byte[] bytes = FileUtils.readBytes(filepath); //(1)构建ClassReader ClassReader cr = new ClassReader(bytes); //(2)构建ClassWriter ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); //(3)串连ClassVisitor int api = Opcodes.ASM9; ClassVisitor cv = new ClassChangeVersionVisitor(api, cw); //(4)结合ClassReader和ClassVisitor int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES; cr.accept(cv, parsingOptions); //(5)生成byte[] byte[] bytes2 = cw.toByteArray(); FileUtils.writeBytes(filepath, bytes2); } } 验证&效果 通过javap -p -v HelloWorld命令可以看到版本号信息已从52调整位51  2.给每个方法添加计算调用时间 对目标类进行方法改造调换---为每个方法添加用时计算 public class HelloWorld { public int add(int a, int b) throws InterruptedException { int c = a + b; Random rand = new Random(System.currentTimeMillis()); int num = rand.nextInt(300); Thread.sleep(100 + num); return c; } public int sub(int a, int b) throws InterruptedException { int c = a - b; Random rand = new Random(System.currentTimeMillis()); int num = rand.nextInt(400); Thread.sleep(100 + num); return c; } } ASM编码实现 public class MethodTimerVisitor2 extends ClassVisitor { private String owner; private boolean isInterface; public MethodTimerVisitor2(int api, ClassVisitor classVisitor) { super(api, classVisitor); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, name, signature, superName, interfaces); owner = name; isInterface = (access & ACC_INTERFACE) != 0; } @Override public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions); if (!isInterface && mv != null && !"<init>".equals(name) && !"<clinit>".equals(name)) { boolean isAbstractMethod = (access & ACC_ABSTRACT) != 0; boolean isNativeMethod = (access & ACC_NATIVE) != 0; if (!isAbstractMethod && !isNativeMethod) { // 每遇到一个合适的方法,就添加一个相应的字段 FieldVisitor fv = super.visitField(ACC_PUBLIC | ACC_STATIC, getFieldName(name), "J", null, null); if (fv != null) { fv.visitEnd(); } mv = new MethodTimerAdapter2(api, mv, owner, name); } } return mv; } private String getFieldName(String methodName) { return "timer_" + methodName; } private class MethodTimerAdapter2 extends MethodVisitor { private final String owner; private final String methodName; public MethodTimerAdapter2(int api, MethodVisitor mv, String owner, String methodName) { super(api, mv); this.owner = owner; this.methodName = methodName; } @Override public void visitCode() { // 首先,处理自己的代码逻辑 super.visitFieldInsn(GETSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应 super.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false); super.visitInsn(LSUB); super.visitFieldInsn(PUTSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应 // 其次,调用父类的方法实现 super.visitCode(); } @Override public void visitInsn(int opcode) { // 首先,处理自己的代码逻辑 if ((opcode >= IRETURN && opcode <= RETURN) || opcode == ATHROW) { super.visitFieldInsn(GETSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应 super.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false); super.visitInsn(LADD); super.visitFieldInsn(PUTSTATIC, owner, getFieldName(methodName), "J"); // 注意,字段名字要对应 } // 其次,调用父类的方法实现 super.visitInsn(opcode); } } } 对方法进行转换 public class HelloWorldTransformCore { private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; public static void main(String[] args) { String relative_path = "sample/HelloWorld.class"; String dir = HelloWorldTransformCore.class.getResource("/").getPath(); String filepath = dir + relative_path; File file = new File(filepath); try { InputStream in = new FileInputStream(file); in = new BufferedInputStream(in); ByteArrayOutputStream bao = new ByteArrayOutputStream(); copyLarge(in, bao, new byte[DEFAULT_BUFFER_SIZE]); byte[] bytes1 = bao.toByteArray(); //(1)构建ClassReader ClassReader cr = new ClassReader(bytes1); //(2)构建ClassWriter ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); //(3)串连ClassVisitor int api = Opcodes.ASM9; ClassVisitor cv = new MethodTimerVisitor2(api, cw); //(4)结合ClassReader和ClassVisitor int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES; cr.accept(cv, parsingOptions); //(5)生成byte[] byte[] bytes2 = cw.toByteArray(); OutputStream out = new FileOutputStream(filepath); BufferedOutputStream buff = new BufferedOutputStream(out); buff.write(bytes2); buff.flush(); buff.close(); System.out.println("file://" + filepath); } catch (IOException e) { e.printStackTrace(); } } public static long copyLarge(final InputStream input, final OutputStream output, final byte[] buffer) throws IOException { long count = 0; int n; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } } 验证结果 public class HelloWorldRun { public static void main(String[] args) throws Exception { // 第一部分,先让“子弹飞一会儿”,让程序运行一段时间 HelloWorld instance = new HelloWorld(); Random rand = new Random(System.currentTimeMillis()); for (int i = 0; i < 10; i++) { boolean flag = rand.nextBoolean(); int a = rand.nextInt(50); int b = rand.nextInt(50); if (flag) { int c = instance.add(a, b); String line = String.format("%d + %d = %d", a, b, c); System.out.println(line); } else { int c = instance.sub(a, b); String line = String.format("%d - %d = %d", a, b, c); System.out.println(line); } } // 第二部分,来查看方法运行的时间 Class<?> clazz = HelloWorld.class; Field[] declaredFields = clazz.getDeclaredFields(); for (Field f : declaredFields) { String fieldName = f.getName(); f.setAccessible(true); if (fieldName.startsWith("timer")) { Object FieldValue = f.get(null); System.out.println(fieldName + " = " + FieldValue); } } } } 3、打印方法参数和返回值 对目标类进行方法改造---为每个方法添加打印入参和出参 public class HelloWorld { public int test(String name, int age, long idCard, Object obj) { int hashCode = 0; hashCode += name.hashCode(); hashCode += age; hashCode += (int) (idCard % Integer.MAX_VALUE); hashCode += obj.hashCode(); return hashCode; } } 我们想实现的预期目标:打印出“方法接收的参数值”和“方法的返回值”。 public class HelloWorld { public int test(String name, int age, long idCard, Object obj) { int hashCode = 0; hashCode += name.hashCode(); hashCode += age; hashCode += (int) (idCard % Integer.MAX_VALUE); hashCode += obj.hashCode(); System.out.println(hashCode); return hashCode; } } 实现这个功能的思路:在“方法进入”的时候,打印出“方法接收的参数值”;在“方法退出”的时候,打印出“方法的返回值”。 首先,我们添加一个ParameterUtils类,在这个类定义了许多print方法,这些print方法可以打印不同类型的数据。 public class ParameterUtils { private static final DateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void printValueOnStack(boolean value) { System.out.println(" " + value); } public static void printValueOnStack(byte value) { System.out.println(" " + value); } public static void printValueOnStack(char value) { System.out.println(" " + value); } public static void printValueOnStack(short value) { System.out.println(" " + value); } public static void printValueOnStack(int value) { System.out.println(" " + value); } public static void printValueOnStack(float value) { System.out.println(" " + value); } public static void printValueOnStack(long value) { System.out.println(" " + value); } public static void printValueOnStack(double value) { System.out.println(" " + value); } public static void printValueOnStack(Object value) { if (value == null) { System.out.println(" " + value); } else if (value instanceof String) { System.out.println(" " + value); } else if (value instanceof Date) { System.out.println(" " + fm.format(value)); } else if (value instanceof char[]) { System.out.println(" " + Arrays.toString((char[])value)); } else { System.out.println(" " + value.getClass() + ": " + value.toString()); } } public static void printText(String str) { System.out.println(str); } } 在下面的MethodParameterVisitor2类当中,我们将使用ParameterUtils类帮助我们打印信息。 ASM编码实现 public class MethodParameterVisitor2 extends ClassVisitor { public MethodParameterVisitor2(int api, ClassVisitor classVisitor) { super(api, classVisitor); } @Override public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions); if (mv != null && !name.equals("<init>")) { boolean isAbstractMethod = (access & ACC_ABSTRACT) != 0; boolean isNativeMethod = (access & ACC_NATIVE) != 0; if (!isAbstractMethod && !isNativeMethod) { mv = new MethodParameterAdapter2(api, mv, access, name, descriptor); } } return mv; } private static class MethodParameterAdapter2 extends MethodVisitor { private final int methodAccess; private final String methodName; private final String methodDesc; public MethodParameterAdapter2(int api, MethodVisitor mv, int methodAccess, String methodName, String methodDesc) { super(api, mv); this.methodAccess = methodAccess; this.methodName = methodName; this.methodDesc = methodDesc; } @Override public void visitCode() { // 首先,处理自己的代码逻辑 boolean isStatic = ((methodAccess & ACC_STATIC) != 0); int slotIndex = isStatic ? 0 : 1; printMessage("Method Enter: " + methodName + methodDesc); Type methodType = Type.getMethodType(methodDesc); Type[] argumentTypes = methodType.getArgumentTypes(); for (Type t : argumentTypes) { int sort = t.getSort(); int size = t.getSize(); String descriptor = t.getDescriptor(); int opcode = t.getOpcode(ILOAD); super.visitVarInsn(opcode, slotIndex); if (sort >= Type.BOOLEAN && sort <= Type.DOUBLE) { String methodDesc = String.format("(%s)V", descriptor); printValueOnStack(methodDesc); } else { printValueOnStack("(Ljava/lang/Object;)V"); } slotIndex += size; } // 其次,调用父类的方法实现 super.visitCode(); } @Override public void visitInsn(int opcode) { // 首先,处理自己的代码逻辑 if ((opcode >= IRETURN && opcode <= RETURN) || opcode == ATHROW) { printMessage("Method Exit: " + methodName + methodDesc); if (opcode >= IRETURN && opcode <= DRETURN) { Type methodType = Type.getMethodType(methodDesc); Type returnType = methodType.getReturnType(); int size = returnType.getSize(); String descriptor = returnType.getDescriptor(); if (size == 1) { super.visitInsn(DUP); } else { super.visitInsn(DUP2); } String methodDesc = String.format("(%s)V", descriptor); printValueOnStack(methodDesc); } else if (opcode == ARETURN) { super.visitInsn(DUP); printValueOnStack("(Ljava/lang/Object;)V"); } else if (opcode == RETURN) { printMessage(" return void"); } else { printMessage(" abnormal return"); } } // 其次,调用父类的方法实现 super.visitInsn(opcode); } private void printMessage(String str) { super.visitLdcInsn(str); super.visitMethodInsn(INVOKESTATIC, "sample/ParameterUtils", "printText", "(Ljava/lang/String;)V", false); } private void printValueOnStack(String descriptor) { super.visitMethodInsn(INVOKESTATIC, "sample/ParameterUtils", "printValueOnStack", descriptor, false); } } } 进行转换 public class HelloWorldTransformCore { public static void main(String[] args) { String relative_path = "sample/HelloWorld.class"; String filepath = FileUtils.getFilePath(relative_path); byte[] bytes1 = FileUtils.readBytes(filepath); //(1)构建ClassReader ClassReader cr = new ClassReader(bytes1); //(2)构建ClassWriter ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); //(3)串连ClassVisitor int api = Opcodes.ASM9; ClassVisitor cv = new MethodParameterVisitor2(api, cw); //(4)结合ClassReader和ClassVisitor int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES; cr.accept(cv, parsingOptions); //(5)生成byte[] byte[] bytes2 = cw.toByteArray(); FileUtils.writeBytes(filepath, bytes2); } } 验证结果 public class HelloWorldRun { public static void main(String[] args) throws Exception { HelloWorld instance = new HelloWorld(); int hashCode = instance.test("Tomcat", 10, System.currentTimeMillis(), new Object()); int remainder = hashCode % 2; if (remainder == 0) { System.out.println("hashCode is even number."); } else { System.out.println("hashCode is odd number."); } } } 四、非顺序结构 1、if语句 public class HelloWorld { public void test(int value) { if (value == 0) { System.out.println("value is 0"); } else { System.out.println("value is not 0"); } } } ASM编码实现 public class HelloWorldGenerateCore { public static void main(String[] args) throws Exception { String relative_path = "sample/HelloWorld.class"; String filepath = FileUtils.getFilePath(relative_path); // (1) 生成byte[]内容 byte[] bytes = dump(); // (2) 保存byte[]到文件 FileUtils.writeBytes(filepath, bytes); } public static byte[] dump() throws Exception { // (1) 创建ClassWriter对象 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); // (2) 调用visitXxx()方法 cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, "sample/HelloWorld", null, "java/lang/Object", null); { MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv1.visitCode(); mv1.visitVarInsn(ALOAD, 0); mv1.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv1.visitInsn(RETURN); mv1.visitMaxs(0, 0); mv1.visitEnd(); } { MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "test", "(I)V", null, null); Label elseLabel = new Label(); Label returnLabel = new Label(); // 第1段 mv2.visitCode(); mv2.visitVarInsn(ILOAD, 1); mv2.visitJumpInsn(IFNE, elseLabel); mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv2.visitLdcInsn("value is 0"); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mv2.visitJumpInsn(GOTO, returnLabel); // 第2段 mv2.visitLabel(elseLabel); mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv2.visitLdcInsn("value is not 0"); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); // 第3段 mv2.visitLabel(returnLabel); mv2.visitInsn(RETURN); mv2.visitMaxs(0, 0); mv2.visitEnd(); } cw.visitEnd(); // (3) 调用toByteArray()方法 return cw.toByteArray(); } } 验证结果 public class HelloWorldRun { public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("sample.HelloWorld"); Object obj = clazz.newInstance(); Method method = clazz.getDeclaredMethod("test", int.class); method.invoke(obj, 0); method.invoke(obj, 1); } } 2、switch语句 public class HelloWorld { public void test(int val) { switch (val) { case 1: System.out.println("val = 1"); break; case 2: System.out.println("val = 2"); break; case 3: System.out.println("val = 3"); break; case 4: System.out.println("val = 4"); break; default: System.out.println("val is unknown"); } } } ASM编码实现 public class HelloWorldGenerateCore { public static void main(String[] args) throws Exception { String relative_path = "sample/HelloWorld.class"; String filepath = FileUtils.getFilePath(relative_path); // (1) 生成byte[]内容 byte[] bytes = dump(); // (2) 保存byte[]到文件 FileUtils.writeBytes(filepath, bytes); } public static byte[] dump() throws Exception { // (1) 创建ClassWriter对象 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); // (2) 调用visitXxx()方法 cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, "sample/HelloWorld", null, "java/lang/Object", null); { MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv1.visitCode(); mv1.visitVarInsn(ALOAD, 0); mv1.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv1.visitInsn(RETURN); mv1.visitMaxs(0, 0); mv1.visitEnd(); } { MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "test", "(I)V", null, null); Label caseLabel1 = new Label(); Label caseLabel2 = new Label(); Label caseLabel3 = new Label(); Label caseLabel4 = new Label(); Label defaultLabel = new Label(); Label returnLabel = new Label(); // 第1段 mv2.visitCode(); mv2.visitVarInsn(ILOAD, 1); mv2.visitTableSwitchInsn(1, 4, defaultLabel, new Label[]{caseLabel1, caseLabel2, caseLabel3, caseLabel4}); // 第2段 mv2.visitLabel(caseLabel1); mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv2.visitLdcInsn("val = 1"); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mv2.visitJumpInsn(GOTO, returnLabel); // 第3段 mv2.visitLabel(caseLabel2); mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv2.visitLdcInsn("val = 2"); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mv2.visitJumpInsn(GOTO, returnLabel); // 第4段 mv2.visitLabel(caseLabel3); mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv2.visitLdcInsn("val = 3"); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mv2.visitJumpInsn(GOTO, returnLabel); // 第5段 mv2.visitLabel(caseLabel4); mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv2.visitLdcInsn("val = 4"); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mv2.visitJumpInsn(GOTO, returnLabel); // 第6段 mv2.visitLabel(defaultLabel); mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv2.visitLdcInsn("val is unknown"); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); // 第7段 mv2.visitLabel(returnLabel); mv2.visitInsn(RETURN); mv2.visitMaxs(0, 0); mv2.visitEnd(); } cw.visitEnd(); // (3) 调用toByteArray()方法 return cw.toByteArray(); } } 验证结果 import java.lang.reflect.Method; public class HelloWorldRun { public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("sample.HelloWorld"); Object obj = clazz.newInstance(); Method method = clazz.getDeclaredMethod("test", int.class); for (int i = 1; i < 6; i++) { method.invoke(obj, i); } } } 3、for语句 public class HelloWorld { public void test() { for (int i = 0; i < 10; i++) { System.out.println(i); } } } ASM编码实现 import org.objectweb.asm.*; import static org.objectweb.asm.Opcodes.*; public class HelloWorldGenerateCore { public static void main(String[] args) throws Exception { String relative_path = "sample/HelloWorld.class"; String filepath = FileUtils.getFilePath(relative_path); // (1) 生成byte[]内容 byte[] bytes = dump(); // (2) 保存byte[]到文件 FileUtils.writeBytes(filepath, bytes); } public static byte[] dump() throws Exception { // (1) 创建ClassWriter对象 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); // (2) 调用visitXxx()方法 cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, "sample/HelloWorld", null, "java/lang/Object", null); { MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv1.visitCode(); mv1.visitVarInsn(ALOAD, 0); mv1.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv1.visitInsn(RETURN); mv1.visitMaxs(0, 0); mv1.visitEnd(); } { MethodVisitor methodVisitor = cw.visitMethod(ACC_PUBLIC, "test", "()V", null, null); Label conditionLabel = new Label(); Label returnLabel = new Label(); // 第1段 methodVisitor.visitCode(); methodVisitor.visitInsn(ICONST_0); methodVisitor.visitVarInsn(ISTORE, 1); // 第2段 methodVisitor.visitLabel(conditionLabel); methodVisitor.visitVarInsn(ILOAD, 1); methodVisitor.visitIntInsn(BIPUSH, 10); methodVisitor.visitJumpInsn(IF_ICMPGE, returnLabel); methodVisitor.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); methodVisitor.visitVarInsn(ILOAD, 1); methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(I)V", false); methodVisitor.visitIincInsn(1, 1); methodVisitor.visitJumpInsn(GOTO, conditionLabel); // 第3段 methodVisitor.visitLabel(returnLabel); methodVisitor.visitInsn(RETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } cw.visitEnd(); // (3) 调用toByteArray()方法 return cw.toByteArray(); } } 验证结果 public class HelloWorldRun { public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("sample.HelloWorld"); Object obj = clazz.newInstance(); Method method = clazz.getDeclaredMethod("test"); method.invoke(obj); } } 4、try-catch语句 public class HelloWorld { public void test() { try { System.out.println("Before Sleep"); Thread.sleep(1000); System.out.println("After Sleep"); } catch (InterruptedException e) { e.printStackTrace(); } } } ASM编码实现 public class HelloWorldGenerateCore { public static void main(String[] args) throws Exception { String relative_path = "sample/HelloWorld.class"; String filepath = FileUtils.getFilePath(relative_path); // (1) 生成byte[]内容 byte[] bytes = dump(); // (2) 保存byte[]到文件 FileUtils.writeBytes(filepath, bytes); } public static byte[] dump() throws Exception { // (1) 创建ClassWriter对象 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); // (2) 调用visitXxx()方法 cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, "sample/HelloWorld", null, "java/lang/Object", null); { MethodVisitor mv1 = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv1.visitCode(); mv1.visitVarInsn(ALOAD, 0); mv1.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv1.visitInsn(RETURN); mv1.visitMaxs(0, 0); mv1.visitEnd(); } { MethodVisitor mv2 = cw.visitMethod(ACC_PUBLIC, "test", "()V", null, null); Label startLabel = new Label(); Label endLabel = new Label(); Label exceptionHandlerLabel = new Label(); Label returnLabel = new Label(); // 第1段 mv2.visitCode(); // visitTryCatchBlock可以在这里访问 mv2.visitTryCatchBlock(startLabel, endLabel, exceptionHandlerLabel, "java/lang/InterruptedException"); // 第2段 mv2.visitLabel(startLabel); mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv2.visitLdcInsn("Before Sleep"); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mv2.visitLdcInsn(new Long(1000L)); mv2.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "sleep", "(J)V", false); mv2.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv2.visitLdcInsn("After Sleep"); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); // 第3段 mv2.visitLabel(endLabel); mv2.visitJumpInsn(GOTO, returnLabel); // 第4段 mv2.visitLabel(exceptionHandlerLabel); mv2.visitVarInsn(ASTORE, 1); mv2.visitVarInsn(ALOAD, 1); mv2.visitMethodInsn(INVOKEVIRTUAL, "java/lang/InterruptedException", "printStackTrace", "()V", false); // 第5段 mv2.visitLabel(returnLabel); mv2.visitInsn(RETURN); // 第6段 // visitTryCatchBlock也可以在这里访问 // mv2.visitTryCatchBlock(startLabel, endLabel, exceptionHandlerLabel, "java/lang/InterruptedException"); mv2.visitMaxs(0, 0); mv2.visitEnd(); } cw.visitEnd(); // (3) 调用toByteArray()方法 return cw.toByteArray(); } } 验证结果 public class HelloWorldRun { public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("sample.HelloWorld"); Object obj = clazz.newInstance(); Method method = clazz.getDeclaredMethod("test"); method.invoke(obj); } } 五、查看class文件的ASM代码 1.打印 当我们想对某一类进行ASM学习或者对想要实现的功能不知道如何实现时可以使用如下类进行ASM代码输出并查看 public class ASMPrint { public static void main(String[] args) throws IOException { // (1) 设置参数 String className = "sample.HelloWorld"; int parsingOptions = ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG; boolean asmCode = true; // (2) 打印结果 Printer printer = asmCode ? new ASMifier() : new Textifier(); PrintWriter printWriter = new PrintWriter(System.out, true); TraceClassVisitor traceClassVisitor = new TraceClassVisitor(null, printer, printWriter); new ClassReader(className).accept(traceClassVisitor, parsingOptions); } } className值设置为类的全限定名,可以是我们自己写的类,例如sample.HelloWorld,也可以是JDK自带的类,例如java.lang.Comparable。 asmCode值设置为true或false。如果是true,可以打印出对应的ASM代码;如果是false,可以打印出方法对应的Instruction。 parsingOptions值设置为ClassReader.SKIP_CODE、ClassReader.SKIP_DEBUG、ClassReader.SKIP_FRAMES、ClassReader.EXPAND_FRAMES的组合值,也可以设置为0,可以打印出详细程度不同的信息。 2.插件 如果你是IDEA可以安装ASM ByteCode Viewer,然后选择要查看得java文件右键选择后可以在右侧看到ASPPlugin上看到对应得ByteCode、ASMified、Groovified。或者是插件ASM Bytecode Outline(本人用得社区版IDEA未达到效果) 六、TreeApi Core API和Tree API的区别 Tree API的优势:易用性:如果一个人在之前并没有接触过Core API和Tree API,那么Tree API更容易入手。功能性:在实现比较复杂的功能时,Tree API比Core API更容易实现。 Core API的优势:执行效率:在实现相同功能的前提下,Core API要比Tree API执行效率高,花费时间少。内存使用:Core API比Tree API占用的内存空间少。 第一点,在ASM当中,不管是Core API,还是Tree API,都能够进行Class Generation、Class Transformation和Class Analysis操作。 第二点,Core API和Tree API是两者有各自的优势。Tree API易于使用、更容易实现复杂的操作;Core API执行速度更快、占用内存空间更少。 这里由于篇幅限制做了删减,如果有兴趣可以联系作者进行交流 七、文中用到的工具类 1、FileUtils public class FileUtils { public static String getFilePath(String relativePath) { String dir = FileUtils.class.getResource("/").getPath(); return dir + relativePath; } } 八、思考对于ASM我们以后能用于做些什么? 1、生成类----根据模版生成类(结合脚手架快速搭建项目以及项目初期模块快速搭建) 2、修改类----根据模版修改类(结合特定结构在java源代码编译生成.class字节码文件时对类进行修改以达到提升系统效率和释放开发人力的目的,可以结合IDEA插件开发开发类似于lombok或更为强大的插件) 作者:京东健康马仁喜 来源:京东云开发者社区 转载请注明来源

优秀的个人博客,低调大师

用强数据类型保护你的表单数据-基于antd表单的类型约束 | 京东云技术团队

概述 接口数据类型与表单提交数据类型,在大多数情况下,大部分属性的类型是相同的,但很少能做到完全统一。 我在之前的工作中经常为了方便,直接将接口数据类型复用为表单内数据类型,在遇到属性类型不一致的情况时会使用any强制忽略类型错误。 后来经过自省与思考,这种工作模式会引起各种隐藏bug,一定有更好的工程解决方案。 我的答案就是:为表单提交数据单独定义类型! 类型解说 接口定义的请求体类型 请求数据类型 type RequestBody = { name?: string count?: number groupIds?: number[] startDate?: string // YYYY-MM-DD } 表单提交数据类型定义 type FormValue = { name?: string count?: number groupIds?: string startDate?: Moment } 有了该类型,我们可以方便的将该类型使用在表单实例上 const [form] = Form.useForm< FormValue >() 类型复用优化 如果表单的数据类型和接口提交的数据类型完全一致,当然可以共用一个,但现实世界这种情况几乎没有。 大多数情况是可以复用一些接口的属性到表单的数据类型中,例如上面的两个数据结构,其中 name、id 属性是相同的,则FormValue 可以优化为 type FormValue = Pick< RequestBody, 'name' | 'count' > { groupIds?: string startDate?: Moment } Form.Item 限定 name 优化 应用此时表单组件的name约束就应为我们自定义的表单数据类型FormValue,定义约束组件 const FormItem = Form.Item as React.FC< Omit< FormItemProps, 'name' > & { name: keyof FormValue } > 应用该约束组件 < FormItem label="名称" name="name" > ... 数据转换 在表单的onFinish提交过程中,需要一个将FormValue(表单数据)转换为RequestBody(提交数据)的函数,类型定义如下: const formValueToRquestBody = (values: FormValue): RequestBody => { return { name: values.name, id: values.id, groupIds: values.groupIds.split(',').map(n => Number(n)), startDate: values.startDate?.format('YYYY-MM-DD'), } } 复杂表单类型 复杂表单有些表单数据并非一层的key => value,而是多层树状或数组结构。 例如:提交数据结构 type FormValue = { name: string rule: { min: number max: number } } 表单中关于rule 的写法为: < Form.Item name={['rule', 'min']}> 这种情况下,name不再是简单的字符串,应该如何用类型约束? 如果可以我希望使用类型工具,兼容多层表单数据结构,但一直没成功。 我目前的方法是,为该表单层级安排一个专用类型,该方法会有些写的麻烦,但胜在能准确的定义好类型。 我在采用该方法校验表单name数据时发现了几个很难发现的拼写错误,提前制止了测试同学提bug过来。 例如为rule属性定义单独的RuleFormItem: import type { FormItemProps } from 'antd' const RuleFormItem = Form.Item as React.FC< Omit< FormItemProps, 'name'> & { name: ['rule', keyof FormValue['rule']] } > 调用时 < RuleFormItem label="min" name={['rule', 'min']}> ... 此时数组中的 rule 与 min 都能收到类型的保护。 泛型抽象 export type TypedFormItem< T > = React.FC< Omit< FormItemProps, 'name' > & { name: T } > 应用泛型 const RuleFormItem = Form.Item as TypedFormItem< keyof FormValue > 🎉🎊 恭喜,现在你的表单已经被类型完整的保护了。 作者:京东零售 王凡 来源:京东有开发者社区 转载请注明来源

优秀的个人博客,低调大师

一种基于闭包函数实现自动化框架断言组件的设计实践 | 京东物流技术团队

1 背景 目前测试组同学基本具备自动化脚本编写能力,为了提高效率,如何灵活运用这些维护的脚本去替代部分手工的重复工作?为了达到测试过程中更多的去使用自动化方式,如何能够保证通过脚本覆盖更多的校验点,提高自动化测试的精度和力度?那么一定是不断的丰富断言,符合预期场景。紧接着棘手的问题就是,在前人维护的脚本不清楚如果在方法内部修改?担心修改原来逻辑影响正向流程运行?一个断言方法希望应用到更多的用例中?本文意在介绍通过闭包函数,实现自动化框架中断言组件的设计实践。 2设计方法 2.1 设计思路 随着脚本维护量不断增大,维护的人越来越多,即要增加断言场景又要保证每天持续集成运行原有用例的成功率。我们理想的断言组件,一定是在不改变原来用例结构和调用方式基础之上,对前人写的代码零侵入,通过装饰器增加更多场景断言,并且做到复用断言组件到更多的测试用例上。 2.2 原理解读 2.2.1 闭包函数解读 名词解释: 闭包函数是函数的嵌套,函数内还有函数,即外层函数嵌套一个内层函数,在外层函数定义局部变量,在内层函数通过nonlocal引用,并实现指定功能,比如计数,最后外层函数return内层函数。 主要作用: 可以变相实现私有变量的功能,即用内层函数访问外层函数内的变量,并让外层函数内的变量常驻内存。 实现原理: 闭包函数之所以可以实现让外层函数内的变量常驻内存,关键就是其定义了个内层函数,并通过内层函数访问外层函数的变量,并最后由外层函数将内层函数返回出去并赋值给另外一个变量。此时因为内层函数被赋值给一个变量,其内存空间不会被释放,而内层函数又在其函数体内引用了外层函数的变量,导致该变量的内存也不会被回收。一般情况下,当一个函数运行完毕后,其内存空间即被回收释放,下次再调用该函数的时候,会重新完整运行一次被调用函数,但闭包函数主要是利用Python的内存回收机制,实现了闭包的效果。 2.2.2 装饰器解读 名词解释: 装饰器自身是一个返回可调用对象的可调用对象,本质是一个闭包函数。 结构特点: 装饰器也是函数的嵌套结构,可能还会存在三层嵌套,外层函数就是装饰器函数,接受的参数是一个函数,一般是传入被装饰函数;内层函数实现具体的装饰器功能,比如日志记录、登录鉴权、逻辑校验等,内层函数return一次传入的函数调用,外层函数return内层函数;如果是多层嵌套,最内层是实现具体装饰器功能的函数,并负责调用一次传入的函数,最外一层函数return第二层函数,依次类推,不过一般最多就是三层函数嵌套。 3 解决方案 3.1 现有用例 def test_enquiry_bill_for_two_driver_quote_price(params): """ 终端来源两个司机同时报价再修改其一报价 Args: params:测试用例数据 Returns:测试用例实际返回结果 """ # 询价接单 enquiry_code = jsf_receive_enquiry_bill(**params['expect'][0]).get("data") params['actual'].append({"enquiryCode": enquiry_code}) # 获取单趟任务 transit_job_code = get_transit_job_code(enquiry_code=enquiry_code).get('transit_job_code') # 司机报名,报价 params['expect'][1].update({"transitJobCode": transit_job_code}) jsf_apply_transit_job_by_param(**params['expect'][1]) # 第二位司机报名,报价 params['expect'][2].update({"transitJobCode": transit_job_code}) jsf_apply_transit_job_by_param(**params['expect'][2]) # 第二位司机修改报价 params['expect'][2].update({"quotePrice": 100}) actual = jsf_apply_transit_job_by_param(**params['expect'][2]) params['actual'].append(actual) assert actual.get('code') == 1 assert actual.get('message') == '重新报价成功' log.info(f'验证预期结果为 {actual.get("data")} 通过') return params 3.2 断言组件设计 单一业务节点校验组件: 如上对询价单报价场景,现有测试用例完全可以单独运行,目前只有简单的返回值断言,缺少很多关键节点校验。比如,步骤一询价接单是否落库成功,步骤二单趟任务是否创建成功;步骤三司机报价后的单趟价格,步骤四司机再次提交报价,调用接口后的价格是否修改成功,我们为了不影响原来用例执行,对原代码做到零侵入,且自动实现断言异常捕获,可以通过增加一个断言组件完成。 def validation(func): @wraps(func) def wrapper(*args, **kwargs): try: # 执行函数 data=func(*args, **kwargs) actual_enquiry=hash_db.query_enquiry_bill(data['actual']['enquiryCode']) actual_transit=hash_db.query_transit_job_bill(data['expect'][1]['transitJobCode']) assert data.get("expect")[2]['quotePrice'] == actual_transit['quote_price'] except Exception as ex: log.exception(ex) return wrapper 公共校验组件: 如上实现了通过一个装饰器去完成断言,但有些同学认为,以上断言方法又不能适用于其他用例,为什么还要额外重写一个函数呢?其实这种方式,更多的会应用到公共组件,比如以下通过装饰器完成用例返回值与对应数据库的断言场景。 def validation_db(sql,**kwargs): def validation(func): @wraps(func) def wrapper(*args, **kwargs): try: counts, results = tms_mysql.execute_query(sql) if counts: # 根据获取数据开始断言 for key_res, value_res in results[0].items(): for key_arg, value_arg in kwargs.items(): if field_change(key_res, change_type='to_arg') == key_arg: log.info(f'断言{key_arg}字段,预期值是{value_res},实际值是{value_arg}') assert value_res == value_arg else: return counts except Exception as ex: log.exception(ex) return wrapper return validation 3.3 改造用例 单一装饰器组件 如下所示,用例test_enquiry_bill_for_two_driver_quote_price内部代码依旧不变,仅是在方法上,加上 @validation,目前在执行原有用例时,增加校验过程数据,比如第一次提交报价的值,更改后提交数据的变化,增加现有自动化测试用例的可靠性。 @validation def test_enquiry_bill_for_two_driver_quote_price(params): """ 终端来源两个司机同时报价再修改其一报价 Args: params:测试用例数据 Returns:测试用例实际返回结果 """ # 询价接单 enquiry_code = jsf_receive_enquiry_bill(**params['expect'][0]).get("data") params['actual'].append({"enquiryCode": enquiry_code}) # 获取单趟任务 transit_job_code = get_transit_job_code(enquiry_code=enquiry_code).get('transit_job_code') # 司机报名,报价 params['expect'][1].update({"transitJobCode": transit_job_code}) jsf_apply_transit_job_by_param(**params['expect'][1]) # 第二位司机报名,报价 params['expect'][2].update({"transitJobCode": transit_job_code}) jsf_apply_transit_job_by_param(**params['expect'][2]) # 第二位司机修改报价 params['expect'][2].update({"quotePrice": 100}) actual = jsf_apply_transit_job_by_param(**params['expect'][2]) params['actual'].append(actual) assert actual.get('code') == 1 assert actual.get('message') == '重新报价成功' log.info(f'验证预期结果为 {actual.get("data")} 通过') return params 多个装饰器嵌套 如下是多个组件嵌套使用方式,及执行顺序解读 @dec1 @dec2 @dec3 def func(): pass 此时:可以对某个被装饰函数,增加多个功能 装饰器生效顺序,从上到下,即dec1>dec2>dec3 在第一步改造后,仅是增加了对核心字段的过程数据校验,有的同学希望用例更加准确,不用再切换去看数据库,直接将所有返回值字段,与库里进行预期比较。 如下所示,同样在原有用例上增加多个装饰器,即多个断言组件,按顺序依次断言。下面是,增加定义的单个用例的私有断言@validation和数据库公共断言@validation_db 增加后不会影响原来测试流程执行,大家也可以按照需求,在断言组件内声明,断言异常是否中断。 @validation @validation_db(enquiry_sql) def test_enquiry_bill_for_two_driver_quote_price(params): """ 终端来源两个司机同时报价再修改其一报价 Args: params:测试用例数据 Returns:测试用例实际返回结果 """ # 询价接单 enquiry_code = jsf_receive_enquiry_bill(**params['expect'][0]).get("data") params['actual'].append({"enquiryCode": enquiry_code}) # 获取单趟任务 transit_job_code = get_transit_job_code(enquiry_code=enquiry_code).get('transit_job_code') # 司机报名,报价 params['expect'][1].update({"transitJobCode": transit_job_code}) jsf_apply_transit_job_by_param(**params['expect'][1]) # 第二位司机报名,报价 params['expect'][2].update({"transitJobCode": transit_job_code}) jsf_apply_transit_job_by_param(**params['expect'][2]) # 第二位司机修改报价 params['expect'][2].update({"quotePrice": 100}) actual = jsf_apply_transit_job_by_param(**params['expect'][2]) params['actual'].append(actual) assert actual.get('code') == 1 assert actual.get('message') == '重新报价成功' log.info(f'验证预期结果为 {actual.get("data")} 通过') return params 4 总结 以上实践案例,是基于运力测试团队现有的自动化维护情况,前期脚本已大量堆砌但缺少断言,现阶段测试流程没有变化,但为了增加自动化脚本的测试力度需要批量增加断言。是否利用装饰器来实现断言,一定要取决于团队中维护用例的情况,如果当前用例从头到尾都是你一个人维护,里面的场景也没办法给其他人公用,那么大可不必!不过学习好装饰器后,在代码编写过程中希望一处实现多处复用,也可以通过装饰器方式去提升代码可读性和可维护性。 作者:京东物流 刘红妍 来源:京东云开发者社区自猿其说Tech 转载请注明来源

资源下载

更多资源
Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码