public final class ClassLoadingUtil
extends java.lang.Object
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!
| Modifier and Type | Method and Description |
|---|---|
static <T> java.lang.Class<T> |
toClass(javassist.CtClass ctClass)
Installs the given
CtClass into the current class-loader and returns
it as a new class. |
static <T> java.lang.Class<T> |
toClass(javassist.CtClass ctClass,
java.lang.ClassLoader loader,
java.security.ProtectionDomain domain)
Installs the given
CtClass into the given class-loader and returns
it as a new class. |
public static <T> java.lang.Class<T> toClass(javassist.CtClass ctClass)
throws javassist.CannotCompileException
CtClass into the current class-loader and returns
it as a new class.T - class typectClass - class to loadjavassist.CannotCompileException - if the class cannot be compiledpublic static <T> java.lang.Class<T> toClass(javassist.CtClass ctClass,
java.lang.ClassLoader loader,
java.security.ProtectionDomain domain)
throws javassist.CannotCompileException
CtClass into the given class-loader and returns
it as a new class.T - class typectClass - class to loadloader - class-loader to install intodomain - protection domain, may be nulljavassist.CannotCompileException - if the class cannot be compiledCopyright © 2017. All Rights Reserved.