Wednesday 22 April 2020

Javassist: Define new class at run time

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

ClassPool is the root class that controls the byte code modifications. It is a container of CtClass objects (CtClass object represent a class file).

Step 2: Use 'makeClass' method to define a class.
CtClass ctClass = pool.makeClass("com.sample.app.model.Point");

Find the below working applicatin.

App.java
package com.sample.app;

import javassist.ClassPool;
import javassist.CtClass;

public class App {

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

  CtClass ctClass = pool.makeClass("com.sample.app.model.Point");
  
  Object obj = ctClass.toClass().newInstance();
  System.out.println("Class Name : " + obj.getClass());
  
  ctClass.writeFile("/Users/Shared/assistDemos");

 }
}

Run App.java, you will see below message 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