javaclassloaderjavassistbytecode-manipulationdynamic-class-loaders

get CtClass using specific ClassLoader


I have a class structure like this:

package com.mydomain.myproject;
public class Outer{
    public class Inner{
        //some code
    }
}

Now, I can get a CtClass of the inner class using:

ClassPool pool=ClassPool.getDefault();
CtClass innerCt=pool.getCtClass("com.mydomain.myproject.Outer$Inner");

The problem occurs if those classes are loaded by a special ClassLoader.

ClassPool#getCtClass fails because the ClassLoader it uses doesn't know of the class.

I get the following exception:

javassist.NotFoundException: com.mydomain.myproject.Outer$Inner
    at javassist.ClassPool.get(ClassPool.java:430)
    at javassist.ClassPool.getCtClass(ClassPool.java:495)
    at <my classes>

How can I specify the ClassLoader for ClassPool#getCtClass? Can I somehow set the class loader of the ClassPool? I noticed that there is a getClassLoader() method but there doesn't seem to be a setter.


Solution

  • ClassPool supports inserting, appending and removing ClassPaths. The ClassPath can be inserted and added in the form of a String or a ClassPath implementation. Removals are only supported in the form of a ClassPath.

    There are 4 supplied implementations of ClassPath:

    1. ByteArrayClassPath: Supply the byte code and class name
    2. ClassClassPath: Supply the Java class
    3. LoaderClassPath: Supply a classloader
    4. URLClassPath: Supply a URL