Get bytes for a class that was generated at runtime

人走茶凉 提交于 2019-12-23 10:20:32

问题


I am working with a Java framework that generates some (proxy) classes at runtime, using a custom ClassLoader. I would like to get for any such class that the custom ClassLoader returns from loadClass(..) the raw byte array that corresponds to this class. Is this possible? I know that if a class exists as a resource then you can use an input stream to load the class in binary format but how can I go about this if the class is generated at runtime?


回答1:


Register a ClassFileTransformer. Rather than modifying the bytes, record the data you need.




回答2:


If you replace the custom ClassLoader with your own, you can add some mechanism for saving the raw bytes yourself.




回答3:


Classes in the ClassLoader are created by the defineClass() method. If you already have a custom classloader you can simply override all of the defineClass() methods. To that method you are passed a byte[] containing the bytes of the class. Store these and you can access them later however you need to for your application.

See [defineClass() Java Documentation][1] for more information.

[1]: http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#defineClass(java.lang.String, byte[], int, int)



来源:https://stackoverflow.com/questions/2074033/get-bytes-for-a-class-that-was-generated-at-runtime

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