Wednesday 22 April 2020

Javassist: Add fields to new class

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

Step 2: Create new class using makeClass method.
CtClass ctClass = pool.makeClass("com.sample.app.model.Point");

Step 3: Define fields using CtField.
CtField xField = new CtField(CtClass.intType, "x", ctClass);
xField.setModifiers(Modifier.PRIVATE);

CtField yField = new CtField(CtClass.intType, "y", ctClass);
yField.setModifiers(Modifier.PRIVATE);

Step 4: Add fields to the class.
ctClass.addField(xField);
ctClass.addField(yField);

Find the below working application.

App.java
package com.sample.app;

import java.lang.reflect.Modifier;

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

public class App {

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

  CtClass ctClass = pool.makeClass("com.sample.app.model.Point");

  CtField xField = new CtField(CtClass.intType, "x", ctClass);
  xField.setModifiers(Modifier.PRIVATE);

  CtField yField = new CtField(CtClass.intType, "y", ctClass);
  yField.setModifiers(Modifier.PRIVATE);

  ctClass.addField(xField);
  ctClass.addField(yField);

  Object obj = ctClass.toClass().newInstance();
  System.out.println("Class Name : " + obj.getClass());

  ctClass.writeFile("/Users/Shared/assistDemos");

 }
}

Run App.java, you will see below messages in console.
Class Name : class com.sample.app.model.Point

You can observe Point.class file is generated at folder /Users/Shared/assistDemos.
$ tree /Users/Shared/assistDemos
/Users/Shared/assistDemos
└── com
    └── sample
        └── app
            └── model
                └── Point.class

4 directories, 1 file

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



Previous                                                    Next                                                    Home

No comments:

Post a Comment