User Tools

Site Tools


technology:java:class_loaders

Java Class Loaders

Most java programs don't need to manipulate the JVM class loader. But there are circumstances when a program needs to load classes in a non-standard way. For example: classes can be loaded from a secured site, or they can be encrypted on disk. In either case, the default class loader must be replaced with a special-purpose one to provide the desired behavior. So, how do we implement our own classloader?

Implementing a Class Loader

So create a basic class loader like this:

package com.freyertech.classloaders;
import java.net.URL;
import java.net.URLClassLoader;
 
public class DoNothingClassLoader extends ClassLoader {
 
    public DoNothingClassLoader() {
        super();
    }
 
    public DoNothingClassLoader(ClassLoader parent) {
        super(parent);
    }
 
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        System.out.println("DoNothingClassLoader was asked to find "+name+".");
        return super.findClass(name);
    }
}

And use it at the command line like this, to call a program with a main() method:

java -Djava.system.class.loader=com.freyertech.classloaders.DoNothingClassLoader MyExample

This will cause the JVM to execute the MyExample class using the class loader created above.

/home/cfreyer/public_html/data/pages/technology/java/class_loaders.txt · Last modified: 2009/04/13 14:21 by Chris Freyer