问题
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:
- ByteArrayClassPath: Supply the byte code and class name
- ClassClassPath: Supply the Java class
- LoaderClassPath: Supply a classloader
- URLClassPath: Supply a URL
来源:https://stackoverflow.com/questions/60789950/get-ctclass-using-specific-classloader