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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:26:31  来源:igfitidea点击:

How to set my custom class loader to be the default?

javatomcatclassloader

提问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.bator $TOMCAT_HOME/bin/run.shexecutable.

由于 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 Loaderelement for your context. The Loader element must be defined inside your Contextelement, wich can be defined at a context.xmlfile. More information:

编辑完成:如果您将类加载器设置为 de System 类加载器,它将用于加载 Tomcat 组件类、不同的库和您自己的类。如果您希望您的类加载器仅用于您的应用程序类(包括库等),您应该Loader为您的上下文配置一个元素。Loader 元素必须在您的Context元素内定义,可以在context.xml文件中定义。更多信息: