alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Java example source code file (Loader2.java)

This example Java source code file (Loader2.java) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Learn more about this Java project at its project page.

Java - Java tags/keywords

checking, class, classloader, classnotfoundexception, defineclass1, fetching, fileinputstream, letting, loader2, resolving, returning, string

The Loader2.java Java example source code

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
public class Loader2 extends ClassLoader {
  int _recur;
  public void print( String msg ) {
    for( int i=0; i<_recur; i++ )
      System.out.print("  ");
    System.out.println(">>Loader2>> "+msg);
  }

  protected Class findClass2(String name) throws ClassNotFoundException {
    print("Fetching the implementation of "+name);
    int old = _recur;
    try {
      FileInputStream fi = new FileInputStream(name+".impl2");
      byte result[] = new byte[fi.available()];
      fi.read(result);

      print("DefineClass1 on "+name);
      _recur++;
      Class clazz = defineClass(name, result, 0, result.length);
      _recur = old;
      print("Returning newly loaded class.");
      return clazz;
    } catch (Exception e) {
      _recur = old;
      print("Not found on disk.");
      // If we caught an exception, either the class was not found or
      // it was unreadable by our process.
      return null;
      //throw new ClassNotFoundException(e.toString());
    }
  }

  protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException  {
    // Attempt a disk load first
    Class c = findClass2(name);
    if( c == null ) {
      // check if the class has already been loaded
      print("Checking for prior loaded class "+name);
      c = findLoadedClass(name);
      print("Letting super-loader load "+name);
      int old = _recur;
      _recur++;
      c = super.loadClass(name, false);
      _recur=old;
    }
    if (resolve) { print("Resolving class "+name); resolveClass(c); }
    print("Returning clazz "+c.getClassLoader()+":"+name);
    return c;
  }
}

Other Java examples (source code examples)

Here is a short list of links related to this Java Loader2.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.