Blog: bugstack.cn

Precipitation, share, grow, let yourself and others can gain something!

directory

  • One, foreword
  • Second, development environment
  • Objective of the case
  • Fourth, technical implementation
  • V. Test results
    • 1. Classes generated using Javassist
    • 2. Output test results
  • Six, summarized

One, foreword

There are three relatively common frameworks for bytecode programming; ASM, byte-Buddy, Javassist, they can all manipulate this bytecode, but in different ways and with different control granularity.

“ASM” is more low-level, requiring knowledge of the specification of the “JVM” virtual machine and knowledge of local variables and operand stacks. Although cumbersome to write, it is also the best performing and most powerful bytecode manipulation framework. It is commonly used in the “CGLIB” dynamic proxy class, as well as in some non-intrusive probe monitoring scenarios.

The other two frameworks have powerful apis that make operation and usage easier to control. Although the performance is somewhat worse than “ASM” for comparison, it is not to say that the performance is completely bad. It is also used very much in some monitoring scenarios. If you are careful, you can search in your project “JAR” package.

I have written some articles on Javaagent full-link monitoring and ASM before this. Although these technical contents are not commonly used in “CRUD” development, with the extensive use of automated testing and non-intrusion monitoring, many people still need to learn such skills. I am also a learner of this skill, and will continue to write and refine this column on bytecode programming. I hope this column will help others grow as well as improve their own technology stack.

“So”, Xiao Fuge plans to finish the whole set of column learning articles successively from Javassist to ASM. From simple entry to application operation, step by step to complete the system of technical knowledge stack learning.

“Good!” , now for the first Helloworld case. The source code can be obtained by following the public account: BugStack wormhole stack

Second, development environment

  1. The JDK 1.8.0 comes with
  2. Javassist 3.12.1. GA
<dependency>

    <groupId>javassist</groupId>

    <artifactId>javassist</artifactId>

    <version>3.12.1. GA</version>

    <type>jar</type>

</dependency>

Copy the code

Objective of the case

Regardless of the implementation, the goal of our case is simple: output a line of Helloworld using JavAssist. That sounds like a product

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Javassist hi helloWorld by Bugstack.cn");

    }



    public HelloWorld(a) {

    }

}

Copy the code

This code is what we need to implement next using bytecode programming techniques.

Fourth, technical implementation

In fact, the output of Helloworld is quite simple, mainly from this to learn the basic syntax structure of Javassist, but also for the following learning a basic concept.

javassist Helloworld

/ * *

* Public id: BugStack wormhole stack

* Blog Stack: https://bugstack.cn - Precipitate, share, grow, let yourself and others learn!

* This column is a technical summary of Xiao Fu Ge's learning process of front-line Internet Java development for many years, aiming to provide you with a clear and detailed learning course. If I can help you, please support (follow, like, share)!

* /


public class GenerateClazzMethod {





    public static void main(String[] args) throws IOException, CannotCompileException, NotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {



        ClassPool pool = ClassPool.getDefault();



        // Create class className: Create the class path and name

        CtClass ctClass = pool.makeClass("org.itstack.demo.javassist.HelloWorld");



        // Add method

        CtMethod mainMethod = new CtMethod(CtClass.voidType, "main".new CtClass[]{pool.get(String[].class.getName())}, ctClass);

        mainMethod.setModifiers(Modifier.PUBLIC + Modifier.STATIC);

        mainMethod.setBody("{system.out.println (\" javAssist hi helloWorld by bugstack.cn)\"); }");

        ctClass.addMethod(mainMethod);



        // Create a no-argument constructor

        CtConstructor ctConstructor = new CtConstructor(new CtClass[]{}, ctClass);

        ctConstructor.setBody("{}");

        ctClass.addConstructor(ctConstructor);



        // Output class content

        ctClass.writeFile();



        // Test the call

        Class clazz = ctClass.toClass();

        Object obj = clazz.newInstance();



        Method main = clazz.getDeclaredMethod("main", String[].class);

        main.invoke(obj, (Object)new String[1]);



    }



}

Copy the code

This code is divided into several pieces of content to achieve the function, including;

  1. Create ClassPool, which is a CtClass object container based on the HashMap implementation.
  2. Using CtClass, create our class information, that is, the path and name of the class.
  3. The next step is to add methods to the class. Including; The properties, type, name, input and output parameters of a method, and the contents of the method body.
  4. After the method is created, you also need to create an empty constructor, which every class generates when compiled.
  5. When the method is created, we usectClass.writeFile()Output method content information. And you can see that through our useJavassistWhat the generated class looks like.
  6. And finally, our reflection callmainMethod to test the output.

V. Test results

When we execute the test, we will output the class information to the project folder, and output our test results;

1. Classes generated using Javassist

Classes generated using Javassist, in the project folder

2. Output test results

Javassist Hi HelloWorld by Bugstack.cn



Process finished with exit code 0

Copy the code

Six, summarized

  • aboutJavassistUse in full and powerfulAPIWell, it’s actually pretty easy to use. And the use of the code is not that hard to understand.
  • In the future, bytecode programming case articles will be published to gradually improve the content of this part of the technical knowledge stack. Finally try to use this technical knowledge to complete a case – level quality inspection system. Also welcome to like this kind of content partners follow up learning.
  • Subsequent articles may be in the column type of articles, the content of the article will be shorter. As far as possible in an article to describe a detailed knowledge point, but also convenient to organize the subsequent PDF books, easy to learn and use.
Bugstack wormhole stack
Precipitation, share, grow, let yourself and others can gain something!
Author Little Fu Ge has been engaged in front-line Internet Java development for many years. From 19 years, he began to compile the technical summary of his work and learning process, aiming to provide you with a clear and detailed core skills learning document. If this article can help you, please support (follow, like, share)!