0

I'm using javassist API to create a method :

CtMethod newmethod = CtNewMethod.make("public boolean preRemove(){return size==getObjectSize();}",ctclass);

this method calls an other method getObjectSize() that exist in that class

in this case I get attempted duplicate class definition for name with LinkageError provoked by this instruction Class clazz = ctclass.toClass();

So, I tried to create my own classLoader CustomClassLoader loader = new CustomClassLoader();

and then I didn't get the new method when I listed the methods of the class

ClassPool pool = ClassPool.getDefault();
CtClass ctclass = pool.get("javaExp.SinglyLinkedList");
ctclass.stopPruning(true);
CtMethod newmethod = CtNewMethod.make("public boolean preRemove(){return size==getObjectSize();}",ctclass);
ctclass.addMethod(newmethod);
ctclass.writeFile();
Class<?> clazz =loader.loadClass("javaExp.SinglyLinkedList");
Method []m=   clazz.getDeclaredMethods(); 
for(int i=0;i<m.length;i++){
System.out.println(m[i].getName());
}

1 Answers1

1

Javassist provides a class loader javassist.Loader. This class loader uses a javassist.ClassPool object for reading a class file.

For example, javassist.Loader can be used for loading a particular class modified with Javassist.

import javassist.*;
import test.Rectangle;

public class Main {
  public static void main(String[] args) throws Throwable {
     ClassPool pool = ClassPool.getDefault();
     Loader cl = new Loader(pool);

     CtClass ct = pool.get("test.Rectangle");
     ct.setSuperclass(pool.get("test.Point"));

     Class c = cl.loadClass("test.Rectangle");
     Object rect = c.newInstance();

  }
}

This program modifies a class test.Rectangle. The superclass of test.Rectangle is set to a test.Point class. Then this program loads the modified class, and creates a new instance of the test.Rectangle class.