You can call a method defined on an anonymous inner class.
News to me. Clever way to define a new class:
private static <T> Class<T> defineClass( ClassLoader parent, final String className, final byte[] bytes) { return new ClassLoader(parent) { public Class defineClass() { return defineClass( className, bytes, 0, bytes.length); } }.defineClass(); }
3 Comments:
Don't you guys think it is a memory leaker? Every new class defined will have its own new class loader.
No. That's the correct way to define new classes when you don't have control of the existing class loader. It's more secure and less error prone than using reflection hacks to forcefully inject a class into the existing loader. The only reason to try to use the existing loader is if you want your new class to be able to access package-private members in a class already loaded in the existing loader (you can't access then across class loader boundaries for security reasons).
Also, forcefully injecting your generated class is more prone to memory leaks. If you generate an unbounded number of classes, they will never get garbage collected, whereas if the class has its own class loader and you no longer have a reference to either, they are candidates for collection.
Post a Comment
<< Home