All analysis using Javassist

Preamble

Compiled class texts in Java, Compiled class texts, Compiled class texts, Impossible re-compilation repairs, Compiled class texts for Javassist`, Compiled class texts for other cans How to increase, and also undemanding deeply entered compiled language, can be generated.

创 KEN class

Maven item, pull-in Javassist 库

<!-- https://mvnrepository.com/artifact/javassist/javassist -->
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>

Use javassist Kenichi Kuruma Personal

package com.y4er.learn;

import javassist.*;


public class CreateClass {
    public static void main(String[] args) throws Exception {
        //Maintenance javassist maintenance pond
        ClassPool pool = ClassPool.getDefault();

        //One individual sky class com.y4er.learn.Person
        CtClass ctClass = pool.makeClass("com.y4er.learn.Person");

        //给 ctClass type addition single string type type character stage name
        CtField name = new CtField(pool.get("java.lang.String"), "name", ctClass);

        //Setting private
        name.setModifiers(Modifier.PRIVATE);

        //Initialization name character stage zhangsan
        ctClass.addField(name, CtField.Initializer.constant("zhangsan"));

        //Generate get, set method
        ctClass.addMethod(CtNewMethod.getter("getName",name));
        ctClass.addMethod(CtNewMethod.setter("setName",name));

        //Additive-free constructor
        CtConstructor ctConstructor = new CtConstructor(new CtClass[]{}, ctClass);
        ctConstructor.setBody("{name=\"xiaoming\";}");
        ctClass.addConstructor(ctConstructor);

        //Additive participation structure
        CtConstructor ctConstructor1 = new CtConstructor(new CtClass[]{pool.get("java.lang.String")}, ctClass);
        ctConstructor1.setBody("{$0.name=$1;}");
        ctClass.addConstructor(ctConstructor1);

        //Jian Jian one public method printName()No participation, no return
        CtMethod printName = new CtMethod(CtClass.voidType, "printName", new CtClass[]{}, ctClass);
        printName.setModifiers(Modifier.PUBLIC);
        printName.setBody("{System.out.println($0.name);}");
        ctClass.addMethod(printName);

        //Copy class text
        ctClass.writeFile();
        ctClass.detach();
    }
}

Person.class image.png

how to use

CtClass representative class, ClassPool CtClass container, ClassPool maintenance CtClass object, demand cautionary measure CtClass quantity over-competition occupancy large amount , CtClass.detach () for demand adjustment.

ClassPool Priority Yes Below Individual Method:

  1. getDefault () Singleton ClassPool
  2. appendClassPath () ClassPath
  3. insertClassPath () Insert ClassPath jar
  4. get () Root name 获tori CtClass object
  5. toClass () General CtClass Converting Class Once converted and cannot be converted
  6. makeClass () New type or interface

Documentation for the migrants: http://www.javassist.org/html/javassist/ClassPool.html

CtClass demand-related method:

  1. addConstructor () Add Constructor
  2. addField () Add character stage
  3. addInterface () Add interface
  4. addMethod () Add method
  5. freeze () Unusable repair repair
  6. defrost () Rehabilitation
  7. detach () 来 ClassPool
  8. toBytecode () Transformed 节 码
  9. toClass () Transform Class object
  10. writeFile () Copy .class text
  11. setModifiers ()

Steps: http://www.javassist.org/html/javassist/CtClass.html

CtMethod Inheritance CtBehavior, Demand-related method:

  1. insertBefore Methodical starting position Insertion fee
  2. insterAfter Representational possession return
  3. insertAt Specified position insertion fee
  4. setBody General method content setting required Copying qualification, this method abstract repair time, the repair mark transfer
  5. make a new method

More steps: http://www.javassist.org/html/javassist/CtBehavior.html

At setBody () Nakaga 们 Used $ code Representative argument

// $0 representative this$1 Representative 1st individual argument analogy
printName.setBody("{System.out.println($0.name);}");

Use CtClass generation object

Above sentence I have generated one ctClass object. Applicable person.class, Person type generation object for adjustment, attribute or method for adjustment?

Three methods:

  1. For reflection method adjustment
  2. Addition class text
  3. Passage interface

For reflex adjustment

//Instance
Object o = ctClass.toClass().newInstance();
Method setName = o.getClass().getMethod("setName", String.class);
setName.invoke(o,"Y4er");
Method printName1 = o.getClass().getMethod("printName");
printName1.invoke(o);

Addition class text

ClassPool pool = ClassPool.getDefault();
pool.appendClassPath("E:\\code\\java\\javassist-learn\\com\\y4er\\learn");
CtClass PersonClass = pool.get("com.y4er.learn.Person");
Object o = PersonClass.toClass().newInstance();
//For subordinate reflex adjustment

For passing interface adjustment

Newly built one interface IPerson, general Person type method can all be abstracted

package com.y4er.learn;

public interface IPerson {
    String getName();

    void setName(String name);

    void printName();
}
ClassPool pool = ClassPool.getDefault();
pool.appendClassPath("E:\\code\\java\\javassist-learn\\com\\y4er\\learn\\Person.class");

CtClass IPerson = pool.get("com.y4er.learn.IPerson");
CtClass Person = pool.get("com.y4er.learn.Person");
Person.defrost();
Person.setInterfaces(new CtClass[]{IPerson});

IPerson o = (IPerson) Person.toClass().newInstance();
o.setName("aaa");
System.out.println(o.getName());
o.printName();

General Person type implementation IPerson interface, direct conversion type at the time of the case, and direct adjustment.

Renovation existing type

javassist The majority of users are renovated and modified, and the user's face is normal. Personal use of self-explanatory solution:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.y4er.learn;

public class Person implements IPerson {
    private String name = "zhangsan";

    public String getName() {
        return this.name;
    }

    public void setName(String var1) {
        this.name = var1;
    }

    public Person() {
        this.name = "xiaoming";
    }

    public Person(String var1) {
        this.name = var1;
    }

    public void printName() {
        System.out.println(this.name);
    }
}

At this time, my thoughts printName

------ printName start ------
xiaoming
------ printName  over ------

Shaichi Shimodai:

pool.appendClassPath("E:\\code\\java\\javassist-learn\\com\\y4er\\learn\\Person.class");
CtClass Person = pool.get("com.y4er.learn.Person");
Person.defrost();

CtMethod printName1 = Person.getDeclaredMethod("printName", null);
printName1.insertBefore("System.out.println(\"------ printName start ------\");");
printName1.insertAfter("System.out.println(\"------ printName  over ------\");");

Object o = Person.toClass().newInstance();
Method printName2 = o.getClass().getMethod("printName");
printName2.invoke(o, null);

Tsujimatsu Realization Completed Face image.png

Recommended Posts

All analysis using Javassist
[Java] Spam judgment using morphological analysis "lucene-gosen"