Create class with javassist and make it available

孤者浪人 提交于 2019-12-01 12:35:18

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.

`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.

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