Monday, 27 April 2020

Javassist: Add static field to a class

Follow below steps to create public static final field in a class.

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: Create new CtField using public static and final modifiers.
CtField ctField = new CtField(CtClass.doubleType, "PI", demoClass);
ctField.setModifiers(Modifier.STATIC | Modifier.FINAL | Modifier.PUBLIC);

Step 4: Add the created field to demoClass.       
demoClass.addField(ctField, "3.14");

Find the below working application.

App.java
package com.sample.app;

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

public class App {

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

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

        CtField ctField = new CtField(CtClass.doubleType, "PI", demoClass);
        ctField.setModifiers(Modifier.STATIC | Modifier.FINAL | Modifier.PUBLIC);
        
        demoClass.addField(ctField, "3.14");

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

    }
}

Run App.java.

You can see 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