我想执行以下操作:
try { Class.forName("MyClass"); } catch(ClassNotFoundException e) { ClassPool pool = ClassPool.getDefault(); CtClass cc = pool.makeClass("MyClass"); Class.forName("MyClass"); }我试过了,但它似乎总是不起作用..它在一个上下文中工作,但在另一个上面相同的代码崩溃在第二个Class.forName(MyClass)...调用 cc.toClass()总是带来正确的类,并尝试过 cc.writeFile(),但它没有任何区别。不知何故,在某些情况下,第二个Class.forName找到了这个类,而在其他情况下它只是打破...我错过了什么?
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"); }调用 toClass 使用适当的类加载器的方法可以解决这个问题......我只是不确定如何控制创建的类可用的类加载器,但是带有类加载器参数的方法可以准确地提供我正在寻找的内容。
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.
更多推荐
使用javassist创建类并使其可用
发布评论