使用javassist创建类并使其可用

编程入门 行业动态 更新时间:2024-10-21 19:02:18
本文介绍了使用javassist创建类并使其可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想执行以下操作:

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创建类并使其可用

本文发布于:2023-10-31 06:20:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545269.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:使其   javassist

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!