错误
如果是web工程,要运行在 tomcat 等容器中,执行下面代码时会报错
ClassPool pool = ClassPool.getDefault();
// 此处报异常,找不到类
CtClass cls = pool.get(clazz.getName());
原因
javassist官网对此有如下说明:
The default ClassPool returned by a static method ClassPool.getDefault() searches the same path that the underlying JVM (Java virtual machine) has. If a program is running on a web application server such as JBoss and Tomcat, the ClassPoolobject may not be able to find user classes since such a web application server uses multiple class loaders as well as the system class loader. In that case, an additional class path must be registered to the ClassPool.
解决方法一(推荐)
ClassPool pool = ClassPool.getDefault();
// 关键代码
ClassClassPath classPath = new ClassClassPath(this.getClass());
pool.insertClassPath(classPath);
解决方法二
ClassPool pool = ClassPool.getDefault();
pool.appendClassPath("E:\\xxx\\xxx\\target\\xxx_war\\WEB-INF\\lib\\xxx_jar-0.0.1-SNAPSHOT.jar");
参考:
https://blog.csdn.net/paincupid/article/details/51175244
https://blog.csdn.net/includei/article/details/109000142