I want to do the following:
try {
Class.forName("MyClass");
} catch(ClassNotFoundException e) {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.makeClass("MyClass");
Class.forName("MyClass");
}
I have tried it, but it doesn't seem to work always... It works in one context, but in the other the same code is crashing on the second "Class.forName("MyClass")"... Calling cc.toClass()
always brings the correct class, and have tried cc.writeFile()
but it makes no difference. Somehow, in some cases the second Class.forName finds the class, and in other cases it just breaks... Am I missing something?
I found out that my code was creating the class on different classloaders depending where I was calling it from. I solved this by doing the following:
try {
Class.forName("MyClass");
} catch(ClassNotFoundException e) {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.makeClass("MyClass");
cc.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain());
Class.forName("MyClass");
}
Calling the toClass
method with the proper Classloader did the trick... I was just unsure on how to control on what classloader the created class would become available, but the method with the classloader parameters allows exactly what I was looking for.