Create class with javassist and make it available

浪尽此生 提交于 2019-12-01 11:02:35

问题


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?


回答1:


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.




回答2:


`try {
    Class.forName("MyClass");
} catch(ClassNotFoundException e) {
try {
    ClassPool pool = ClassPool.getDefault();
    CtClass cc = pool.makeClass("MyClass");
    Class.forName("MyClass");
catch(Exception e) {
}
}`

Check with this code, sometime jvm optimize the code and shuffle the statements , except in try block.



来源:https://stackoverflow.com/questions/26606450/create-class-with-javassist-and-make-it-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!