Monday 27 April 2020

Javassist: add field of type list to a class

Follow below steps.

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

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

Step 3: Get CtClass instance of List.
CtClass arrListClazz = ClassPool.getDefault().get("java.util.List");

Step 4: Add arrListClazz to demoClass
CtField ctField = new CtField(arrListClazz, "myList", demoClass);

Step 5: Add field to demoClass.
demoClass.addField(ctField);

Find the below working application.

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 demoClass = classPool.makeClass("com.sample.app.model.Demo");

        CtClass arrListClazz = ClassPool.getDefault().get("java.util.List");
        CtField ctField = new CtField(arrListClazz, "myList", demoClass);

        demoClass.addField(ctField);

        demoClass.writeFile("/Users/Shared/javassist");
    }
}

Run App.java.

You can observe Demo.class file is created in folder /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, you can see the source code.




Previous                                                    Next                                                    Home

No comments:

Post a Comment