Wednesday, February 15, 2006

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);


Blogger Sam Pullara said...

That kicks ass.

4:06 PM  
Blogger Eugene Kuleshov said...

Don't you guys think it is a memory leaker? Every new class defined will have its own new class loader.

10:34 PM  
Blogger Bob Lee said...

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).

7:56 AM  
Blogger Bob Lee said...

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.

7:59 AM  

Post a Comment

Links to this post:

Create a Link

<< Home