Monday, November 17, 2008

Which Class Loader Should I use?

Every Java developer knows thing or two about class loaders in the Java. I am sure there are plenty of articles out there to tell you more about "What class loaders are?" and their significance in the Java language. In this article I would like to go over various different ways you can get hands on a class loader, and which method I use and when and why?

There are two elements you need to know before you can load a class or resource, in a Java application
1) Name of the resource.
2) Location of the resource.

Depending upon the application, developer may or may not know above settings at design time of an application. Below we will discuss, which technique to use depending upon the situation

For example purpose let's assume that there is interface "Foo" and it has corresponding implementation class "FooImpl"

If you know the name and location, then it is pretty simple.

Foo foo = new FooImpl();

If you do not know the name, however if you *know* that resource will be reachable from the same class loader as the executing class, then you can code as below

Class fooClazz = this.getClass().getClassLoader().loadClass("FooImpl");
Foo foo = fooClazz.newInstance(); // assuming there is default constructor


Class fooClazz = Class.forName("FooImpl");
Foo foo = fooClazz.newInstance();

If you do not know both the name and location of resource, then it becomes little complicated. Usually this occurs when you are using some framework code, and writing some extensions and you do not have control over how your resources are being loaded (for example in application server) then the above techniques work some times, but below should be safer option

Class fooClazz = Thread.currentThread().getContextClassLoader().loadclass("FooImpl");
Foo foo = fooClazz.newInstance();

When the executing thread gets created it will be assigned class loader of the executing class, however user could be set to any other class loader at any point depending upon needs giving the most flexibility.

No comments: