com.genedavis.util.ClassLoaders

This class is for the loading of classes dynamically that are not in the class path. Feel free to reuse this code.

Typically I use it like this. I write an interface that is not in a package. Then I write classes that extend that interface. I put them in a subfolder in the program that I’m writing. I then search that directory at runtime for any classes. I try to load them using com.genedavis.util.ClassLoaders and then try casting them to the interface type I implemented them as. If that all works, I then use them to extend the program I’ve written.

//
//  ClassLoaders.java
//  
//  Created by T. Gene Davis on Sat Aug 18 2001.

package com.genedavis.util;

import java.io.*;
import java.util.*;

public class ClassLoaders extends ClassLoader{
    public Object loadClassFromFile(String className, File classFile) {
        Object returnValue = null;
        try {
            byte[] newClass =  null;

            FileInputStream fis = new FileInputStream(classFile);

            int nextByte = 0;
            Vector vic = new Vector();
            do {
                nextByte = fis.read();
                if (nextByte != -1) vic.add(new Byte( (byte) nextByte ));
            } while(nextByte != -1);

            newClass = new byte[vic.size()];
            for(int z=0; z<vic.size();z++) {
                newClass[z] = ((Byte) vic.get(z)).byteValue();
            }

            returnValue = (this).defineClass(className, newClass, 0, newClass.length).newInstance();
        } catch (Exception e) {}
        return returnValue;
    }
}