Tuesday 21 April 2020

Javassist: Write .class file of a class to a file

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: Read class file from the source.
CtClass cc = pool.get("com.sample.app.model.Employee");

‘pool.get()’ method reads a class file from the source and returns a reference to the CtClass object representing that class file.  If that class file has been already read, this method returns a reference to the CtClass created when that class file was read at the first time.

‘pool.get’ method searches the default system search path to find the class.

Step 3: Write the class file to a directory.
cc.writeFile("/Users/Shared/assistDemos");

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.io.IOException;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;

public class App {
 public static void main(String args[]) throws NotFoundException, CannotCompileException, IOException {
  ClassPool pool = ClassPool.getDefault();
  CtClass cc = pool.get("com.sample.app.model.Employee");
  cc.writeFile("/Users/Shared/assistDemos");
  
 }
}

Run App.java

Open the directory '/Users/Shared/assistDemos', you can see Employee.class file is generated.

$tree /Users/Shared/assistDemos
/Users/Shared/assistDemos
└── com
    └── sample
        └── app
            └── model
                └── Employee.class

4 directories, 1 file




Previous                                                    Next                                                    Home

No comments:

Post a Comment