Saturday, 2 May 2020

Javassist: Add new fields to existing class

Step 1: Instantiate ClassPool object.
ClassPool pool = ClassPool.getDefault();

Step 2: Get CtClass instance
CtClass ctClass = pool.get("com.sample.app.model.Employee");

Step 3: Define a field           
CtField ctField = new CtField(CtClass.doubleType, "salary", ctClass);
ctField.setModifiers(Modifier.PUBLIC);

Step 4: Add this field to CtClass instace.
ctClass.addField(ctField);

Find the below working application.

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

public class Employee {
 private int id;
 private String name;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

}

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.get("com.sample.app.model.Employee");
  
  CtField ctField = new CtField(CtClass.doubleType, "salary", ctClass);
  ctField.setModifiers(Modifier.PUBLIC);
  
  ctClass.addField(ctField);
  ctClass.writeFile("/Users/Shared/assistDemos");
 }
}

Run App.java.

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

4 directories, 1 file
Open Employee.class file in java decompiler to see the source code.

Previous                                                    Next                                                    Home

No comments:

Post a Comment