Saturday, 2 May 2020

Javassist: Remove CtClass object from ClassPool

If number of CtClass objects handled by ClassPool object are large, then you may end up in high menory memory consumption problems. To solve this, whenever you do not need CtClass objects, remove them from the pool explicitly.

How to remove a CtClass from ClassPool?
Using dtach method of CtClass, you can remove the CtClass object from pool.

Example
CtClass ctClass = ... ;
ctClass.detach();

App.java
package com.sample.app;

import javassist.ClassPool;
import javassist.CtClass;

public class App {

 public static void main(String args[]) throws Exception {

  ClassPool classPool = ClassPool.getDefault();
  classPool.makeClass("com.sample.app.model.Point");

  CtClass ctClass1 = classPool.get("com.sample.app.model.Point");

  System.out.println("Class Name : " + ctClass1.getName());

  System.out.println("Detaching the class from pool");
  ctClass1.detach();

  System.out.println("Retrieving the ctClass from pool");
  CtClass ctClass2 = classPool.get("com.sample.app.model.Point");

  System.out.println("ctClass2 : " + ctClass2);
 }
}

Run App.java, you will get below messages in console.

Class Name : com.sample.app.model.Point
Detaching the class from pool
Retrieving the ctClass from pool
Exception in thread "main" javassist.NotFoundException: com.sample.app.model.Point
         at javassist.ClassPool.get(ClassPool.java:430)
         at com.sample.app.App.main(App.java:21)




Previous                                                    Next                                                    Home

No comments:

Post a Comment