get CtClass using specific ClassLoader

ぐ巨炮叔叔 提交于 2021-02-10 18:44:44

问题


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: io.github.jdiscordbots.nightdream.commands.Eval$Sandbox
    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.


回答1:


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


来源:https://stackoverflow.com/questions/60789950/get-ctclass-using-specific-classloader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!