我想从字节数组加载 Tomcat 中的新类(之前未加载)。我也引用了 tomcat 应用程序类加载器。 我将我的自定义类加载器声明为
class CustomClassLoader extends ClassLoader{
public CustomClassLoader(ClassLoader classLoader) {
super(classLoader);
}
public Class loadThisClass(String name){
//get .class byte array in data.
Class clazz = defineClass(name, data, 0, data.length, null);
resolveClass(clazz);
return clazz;
}
}
我正在使用这个类加载器作为
CustomClassLoader customClassLoader = new CustomClassLoader(getClass().getClassLoader());
/*
print getClass().getClassLoader() and it output as
WebappClassLoader
context: /test
delegate: false
repositories:
/WEB-INF/classes/
----------> Parent Classloader:
org.apache.catalina.loader.StandardClassLoader@52e99642
*/
Class clazz = customClassLoader.loadThisClass("com.Class1");
//print clazz.getMethods, it print my new method.
当我尝试如下检查这个类时
Class.forName("com.Class1");
我收到 ClassNotFoundException 并且 Web 应用程序中的其他类无法访问此类。
我如何在 tomcat 网络应用程序中定义可供我的网络应用程序中的其他类访问的新类。。
最佳答案
这可能还不够,但您不需要在 Classloader 中重写 findClass
吗? ?
protected Class findClass(String name) throws ClassNotFoundException
Finds the class with the specified binary name. This method should be overridden by class loader implementations that follow the delegation model for loading classes, and will be invoked by the loadClass method after checking the parent class loader for the requested class. The default implementation throws a ClassNotFoundException.
评论回复:
Prohibited package name : java.lang
意味着您试图从您自己的类加载器加载 java.lang 包空间中的类。 java.lang 包中是类加载器还是你要加载的类?
如果不是,你的类加载器可能试图加载太多。在您覆盖的 findClass 中,您应该检查它是否在您的域中,如果不在则抛出。
protected Class<?> findClass(String name) {
if(!name.startsWith("com.your.package")) throw new ClassNotFoundException();
}
关于java - 在 Tomcat 中定义新类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26520904/