Tuesday 21 April 2020

Javassist: Get the modified byte code

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 ctClass = 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: Set super class to this class.
ctClass.setSuperclass(pool.get("com.sample.app.model.BaseEntity"));

Step 4: Call toBytecode method to get the byte code of class.
byte[] byteCode = ctClass.toBytecode();

Find the below working application.

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

public class BaseEntity {
 private String createdBy;
 private String updatedBy;

 public String getCreatedBy() {
  return createdBy;
 }

 public void setCreatedBy(String createdBy) {
  this.createdBy = createdBy;
 }

 public String getUpdatedBy() {
  return updatedBy;
 }

 public void setUpdatedBy(String updatedBy) {
  this.updatedBy = updatedBy;
 }

}

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 javassist.ClassPool;
import javassist.CtClass;

public class App {

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

  CtClass ctClass = pool.get("com.sample.app.model.Employee");
  ctClass.setSuperclass(pool.get("com.sample.app.model.BaseEntity"));

  byte[] byteCode = ctClass.toBytecode();

  String str = new String(byteCode);
  System.out.println(str);

 }
}



Previous                                                    Next                                                    Home

No comments:

Post a Comment