org.iternine.jeppetto.enhance
Class ClassLoadingUtil

java.lang.Object
  extended by org.iternine.jeppetto.enhance.ClassLoadingUtil

public final class ClassLoadingUtil
extends Object

Provides utility methods for defining javassist CtClass objects in arbitrary ClassLoaders.

This class is needed to define classes that sub-class those loaded in the system classloader. For example, given a class Foo, and the code:

 CtClass myFooExtension = ...; // use javassist to 'extend' Foo and inject bytecode
 Class cls = myFooExtension.toClass();
 Foo foo = (Foo) cls.newInstance();
 
The last line of this sample code would throw a ClassCastException because Foo, on the left, was loaded by the system classloader and MyFooExtension, on the right, was loaded in another classloader.

To work around this, use this utility:

 CtClass myFooExtension = ...; // same as above
 Class cls = ClassLoadingUtil.toClass(myFooExtension, Foo.class.getClassLoader(), null);
 Foo foo = (Foo) cls.newInstance();
 

And enjoy!


Method Summary
static
<T> Class<T>
toClass(javassist.CtClass ctClass)
          Installs the given CtClass into the current class-loader and returns it as a new class.
static
<T> Class<T>
toClass(javassist.CtClass ctClass, ClassLoader loader, ProtectionDomain domain)
          Installs the given CtClass into the given class-loader and returns it as a new class.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

toClass

public static <T> Class<T> toClass(javassist.CtClass ctClass)
                        throws javassist.CannotCompileException
Installs the given CtClass into the current class-loader and returns it as a new class.

Type Parameters:
T - class type
Parameters:
ctClass - class to load
Returns:
new class
Throws:
javassist.CannotCompileException - if the class cannot be compiled

toClass

public static <T> Class<T> toClass(javassist.CtClass ctClass,
                                   ClassLoader loader,
                                   ProtectionDomain domain)
                        throws javassist.CannotCompileException
Installs the given CtClass into the given class-loader and returns it as a new class.

Type Parameters:
T - class type
Parameters:
ctClass - class to load
loader - class-loader to install into
domain - protection domain, may be null
Returns:
new class
Throws:
javassist.CannotCompileException - if the class cannot be compiled


Copyright © 2012. All Rights Reserved.