Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

Are the answers to the above will be different in case of standalone app?

Thanks!

like image 867
Seffy Avatar asked Sep 27 '10 07:09

Seffy


People also ask

How do I use a custom class loader?

The BootStrap class will dynamically load the target. jar and spring-context jar files by the same classloader which is a URLClassLoader instance. Because of this, the method start in Target instance can access the DateFormatter class that is defined in spring-context . Finally, run the BootStrap main method.

Can we create custom class loader?

To create a custom class loader, we will create a class that will extend ClassLoader. There is a method findClass() that must be overridden. Create a method that will load your given class from the class path. In our case we have created the method loadClassData() that will return byte[].

What is the use of ClassLoader in Java?

The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. The Java run time system does not need to know about files and file systems because of classloaders. Java classes aren't loaded into memory all at once, but when required by an application.


Video Answer


1 Answers

You can set the system default class loader as a JVM argument:

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.

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:

  • 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 own Context.
like image 84
Tomas Narros Avatar answered Sep 18 '22 10:09

Tomas Narros