DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

serious has posted 1 posts at DZone. View Full User Profile

FileClassLoader

08.14.2008
| 3567 views |
  • submit to reddit
        Sample class loader written in Java.

package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileClassLoader extends ClassLoader {

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        Class<?> clazz = findLoadedClass(name);
        if (clazz == null) {
            clazz = findSystemClass(name);
            if (clazz == null) {
                String fileName = name.replace('.', File.separatorChar) + ".class";
                byte[] classData = loadClassData(fileName);
                clazz = defineClass(name, classData, 0, classData.length);
            }
        }
        return clazz;
    }

    private byte[] loadClassData(String fileName) throws ClassNotFoundException {
        InputStream inputStream = null;
        byte[] classData = null;
        try {
            File file = new File(fileName);
            inputStream = new FileInputStream(file);
            int fileSize = (int) file.length();
            classData = new byte[fileSize];
            inputStream.read(classData, 0, fileSize);
        } catch (IOException e) {
            throw new ClassNotFoundException("Cannot read class data", e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new ClassNotFoundException("Cannot read class data", e);
            }
        }
        return classData;
    }
}