1 Reply Latest reply: May 16, 2006 10:14 AM by Yanic Inghelbrecht RSS

ont-the-fly generation of class with protected constructor i

Yanic Inghelbrecht Newbie

Assume the following class 'ClassWithProtectedConstructor':

public class ClassWithProtectedConstructor {
 protected ClassWithProtectedConstructor() {
 super();
 }
}


Dynamically generating a subclass of the above doesn't seem to work because there is no public constructor, as the following test case demonstrates :

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtField;
import javassist.CtNewClass;
import javassist.NotFoundException;
import junit.framework.TestCase;

public class TestProtectedSuperclassConstructor extends TestCase {
 public void test() throws NotFoundException, CannotCompileException {
 ClassPool pool=ClassPool.getDefault();

 CtNewClass recursiveClass = new CtNewClass("RecursiveClass", pool , false, pool.get("ClassWithProtectedConstructor"));
 recursiveClass.toClass();
 }
}


The call to 'toClass()' produces the following exception stack trace :

javassist.CannotCompileException: by javassist.CannotCompileException: no public constructor in ClassWithProtectedConstructor
at javassist.ClassPool.toClass(ClassPool.java:816)
at javassist.ClassPool.toClass(ClassPool.java:765)
at javassist.CtClass.toClass(CtClass.java:985)
at TestProtectedSuperclassConstructor.test(TestProtectedSuperclassConstructor.java:13)

(rest of stack trace omitted)

Any insights into the reason for this limitation would be much appreciated.