Javassist: re-creating a class - delete first, or defrost() and modify?

∥☆過路亽.° 提交于 2020-01-01 03:24:07

问题


I use Javassist to create a class. And in a test suite, when a second test tries to create the same class, it fails at pool.makeClass( ... ) because the class is frozen (i.e. already created via toClass().

What's the way to overcome this? Ideally, the first test should delete the class somehow - perhaps unload from the classloader - but as I read in JLS, the unload operation is not reliable.

So perhaps the workaround is to check in the class creating code whether it exists, and if it does, defrost() it, remove all members etc, and re-create it.

Any other ideas?

Or is there some reliable way to delete the class through Javassist?


回答1:


You cannot unload a single class from a ClassLoader. A class may be unloaded if it and its ClassLoader became unreachable but since every class refers to its loader that implies that all classes loaded by this loader must have become unreachable too.

But you can (re-)create the class using a different ClassLoader. Well, formally it is a different class with the same name (and maybe the same byte code) then. If the code executed within the test case leaves no references in the heap, the ClassLoader and its classes might be collected after the test.




回答2:


I get the same problem, i solved it this way, may be cannot apply for your test case:

Make CtClass a private static variable of your Class.

Create a method that check's if CtClass is already built. If CtClass is not built, call the method that builds it, else, return that CtClass.

Make that all your test use the new method.

So, if you have N Test, just the first one will attempt to Built the CtClass, the rest of them will have the static CtClass Variable.



来源:https://stackoverflow.com/questions/17323300/javassist-re-creating-a-class-delete-first-or-defrost-and-modify

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