Tuesday, 21 April 2020

Javassist: Add super class to a class

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

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

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 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.setSuperclass(pool.get("com.sample.app.model.BaseEntity"));
  
  cc.writeFile("/Users/Shared/assistDemos");
  
 }
}

Run App.java.

Open the generated .class file in java decompiler, you can confirm that the class Employee extends BaseEntity.



Previous                                                    Next                                                    Home

No comments:

Post a Comment