java 如何将我的自定义类加载器设置为默认值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3801714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set my custom class loader to be the default?
提问by Seffy
I'm trying to practice myself with custom class loaders, and I've some questions. Is there a way to indicate the JVM to use my custom class loader globally? For example, I wrote small app running under Tomcat 6. The servlet is managed by the container, where should I set my class loader? In addition, the webapp uses some 3rd party jars, can I control the classes loading of those jars?
我正在尝试使用自定义类加载器来练习自己,但我有一些问题。有没有办法指示 JVM 全局使用我的自定义类加载器?比如我写了一个运行在Tomcat 6下的小app,servlet是由容器管理的,我的类加载器应该在哪里设置呢?另外,webapp 使用了一些 3rd 方 jar,我可以控制这些 jar 的类加载吗?
Are the answers to the above will be different in case of standalone app?
在独立应用程序的情况下,上述答案是否会有所不同?
Thanks!
谢谢!
回答by Tomas Narros
You can set the system default class loader as a JVM argument:
您可以将系统默认类加载器设置为 JVM 参数:
java -Djava.system.class.loader
=com.test.YourCustomClassLoader com.test.YourMainClass
As Tomcat starts as a java application, you can set this parameter too, at the %TOMCAT_HOME%\bin\run.bat
or $TOMCAT_HOME/bin/run.sh
executable.
由于 Tomcat 作为 Java 应用程序启动,因此您也可以在%TOMCAT_HOME%\bin\run.bat
或$TOMCAT_HOME/bin/run.sh
可执行文件中设置此参数。
Edit for completion:If you set your classloader as de System class loader, it will be used to load Tomcat component classes, the different libraries, and your own classes.
If you want your class loader to be used only for your application classes (including libraries and so), you should configure a Loader
element for your context.
The Loader element must be defined inside your Context
element, wich can be defined at a context.xml
file.
More information:
编辑完成:如果您将类加载器设置为 de System 类加载器,它将用于加载 Tomcat 组件类、不同的库和您自己的类。如果您希望您的类加载器仅用于您的应用程序类(包括库等),您应该Loader
为您的上下文配置一个元素。Loader 元素必须在您的Context
元素内定义,可以在context.xml
文件中定义。更多信息:
- Apache Tomcat: Class Loader HOW-TO: defines how the ClassLoaders work in Tomcat.
- Tomcat Configuration Reference: The Context Container: how to define your
Context
element - Tomcat Configuration Reference: The Loader Component: How to define your custom
Loader
element for your ownContext
.
- Apache Tomcat:类加载器 HOW-TO:定义类加载器在 Tomcat 中的工作方式。
- Tomcat 配置参考:上下文容器:如何定义您的
Context
元素 - Tomcat 配置参考:加载程序组件:如何
Loader
为您自己的Context
.