Byte Buddy - Handling cyclic references in generated classes

放肆的年华 提交于 2019-12-11 05:26:49

问题


I'm trying to generate runtime wrappers around classes in some class graph, but I don't know how to handle the situation when there is a cycle in the graph. Imagine there's a class A that has a field of type B, but type B has a field of type A. I want to generate classes A' and B' so that class A' has a field of type B' and B' has a field of type A'. In Byte Buddy the method "defineField" can receive a parameter of type TypeDefinition. I think there must be a way to define TypeDefinition for a type that isn't defined yet, but I cannot find it yet.


回答1:


You can define such a field with TypeDescription.Latent but this is at your own risk. Byte Buddy treats this as a specific, unvalidated use case as type redefinition is quite complex considering the interdepencdency.

Make sure that you do not load a type before defining the latent type properly. Also, you probably need to combine the two types into a single DynamicType.Unloaded via the include method. Furthermore, you should note that the ClassLoadingStrategy.Default.INJECT strategy might not work if the VM in question validates the injected type eagerly. As you can only inject one type at a time, in circular type definitions, at least one type will always be missing at the time of injection the first type. Consider using the ClassLoadingStrategy.Default.WRAPPER strategy which does not suffer this limitation.

This said, you can do this without any problems but you can experience VerifierErrors what is something that you are normally promised to not experience.



来源:https://stackoverflow.com/questions/40094448/byte-buddy-handling-cyclic-references-in-generated-classes

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