Monday, 27 April 2020

Javassist: Add non-primitive fields to a class

Follow below step by step procedure to add non-primitive field to a class.

Step 1: Define Class Point.
public class Point {
    .....
    .....
}

Step 2: Get an instance of ClassPool.
ClassPool classPool = ClassPool.getDefault();

Step 3: Get CtClass instance.
CtClass ctClass = classPool.makeClass("com.sample.app.model.Demo");

Step 4: Get CtClass instance for Point class.
CtClass pointClass = classPool.get("com.sample.app.model.Point");

Step 5: Define CtField using pointClass.
CtField ctField = new CtField(pointClass, "point", ctClass);

Step 6: Add the field to CtClass.
ctClass.addField(ctField);

Find the below working application.

Point.java
package com.sample.app.model;

public class Point {
    private int x;
    private int y;

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

}

App.java
package com.sample.app;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;

public class App {

    public static void main(String args[]) throws Exception {
        ClassPool classPool = ClassPool.getDefault();

        CtClass ctClass = classPool.makeClass("com.sample.app.model.Demo");

        CtClass pointClass = classPool.get("com.sample.app.model.Point");
        CtField ctField = new CtField(pointClass, "point", ctClass);

        ctClass.addField(ctField);
        
        ctClass.writeFile("/Users/Shared/javassist");
    }
}

Run App.java.

You can observe Demo.class file is created at "/Users/Shared/javassist".
$tree /Users/Shared/javassist
/Users/Shared/javassist
└── com
    └── sample
        └── app
            └── model
                └── Demo.class

4 directories, 1 file

Open Demo.class file in java decompiler to see the source code.


Previous                                                    Next                                                    Home

No comments:

Post a Comment