Advertisement
jdalbey

ClassFetcher source code

Jan 15th, 2015
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.89 KB | None | 0 0
  1. package com.horstmann.violet.framework;
  2. import java.io.*;
  3. import java.net.*;
  4.  
  5. /**
  6.  *  Dynamically load a class, given its location in the filesystem.
  7.  *  @author jdalbey
  8.  *  @version 0.1
  9.  */
  10. public final class ClassFetcher
  11. {
  12.     private static final String kPkgSeparator = ".";
  13.  
  14.     /** Dynamically load a compiled Java class, given the
  15.      * absolute path to the .class file.  For example, if the package animals
  16.      * contains the class Wombat, the compiled class file might be located at
  17.      * /home/joe/java/animals/Wombat.class.  Given this path, this method will
  18.      * return the Class animals.Wombat.
  19.      * This implementation tries all variations of path name
  20.      * and package name until it finds the one that works.
  21.      * It assumes the .class file is in the correct location in the filesystem
  22.      * hierarchy.
  23.      * @param absolutePath filesystem path to the desired .class file.  The path
  24.      *        may be anywhere on the filesystem, it is not limited to the
  25.      *        current classpath. Precondition: path must begin with File.separator
  26.      *        and end with ".class"
  27.      * @return the Class type for the specified .class file,
  28.      *         or null if the Class couldn't be loaded.
  29.      */
  30.     public static Class<?> loadClass(String absoluteFilePath)
  31.     {
  32.         // remove file extension, leaving /home/joe/birds/Robin
  33.         int end = absoluteFilePath.lastIndexOf(kPkgSeparator);
  34.         String directory = absoluteFilePath.substring(0,end);
  35.         // at the last separator, divide the directory name into two parts
  36.         end = directory.lastIndexOf(File.separator);
  37.         String lastPart = directory.substring(end+1);
  38.         // Make the last part the class name
  39.         String canonicalClassName = lastPart;
  40.         // Make the front part the directory path
  41.         directory = directory.substring(0,end);
  42.  
  43.         // Declare an array of URL's, even though we are only using one,
  44.         // because an array is required for URLClasssLoader constructor
  45.         URL[] urls = null;
  46.         // The classloader we will use to try to find the target class
  47.         ClassLoader cl = null;
  48.         // If successful, the resulting class
  49.         Class<?> dynamicClass = null;
  50.         /* Iteratively work our way up the directory path, trying each segment
  51.          * in turn as if it's the base, and the remainder is the package.
  52.          */
  53.         while (directory.length() > 1 && dynamicClass == null)
  54.         {
  55.             try
  56.             {
  57.                 // Convert directory to a URL (array will have a single element)
  58.                 urls = new URL[]{new File(directory).toURI().toURL()};
  59.  
  60.                 // Create a new class loader with the directory url
  61.                 cl = new URLClassLoader(urls);
  62.  
  63.                 // Attempt to load the class
  64.                 dynamicClass = cl.loadClass(canonicalClassName);
  65.                 // If we get here, we succeeded    
  66.             }
  67.             catch (MalformedURLException ex)
  68.             {
  69.                 ex.printStackTrace();
  70.             }
  71.             // Thrown when the file doesn't exist
  72.             catch (ClassNotFoundException ex)
  73.             {
  74.                 ex.printStackTrace();
  75.             }
  76.             // Thrown if the file exists but the package the loader was using doesn't match.
  77.             catch (NoClassDefFoundError ex)
  78.             {
  79.                 // At the last separator, divide the directory name into two parts
  80.                 end = directory.lastIndexOf(File.separator);
  81.                 lastPart = directory.substring(end+1);
  82.                 // Add the last part to the class name
  83.                 canonicalClassName = lastPart + kPkgSeparator + canonicalClassName;
  84.                 // Make the front part the directory path
  85.                 directory = directory.substring(0,end);            
  86.             }
  87.         } // end loop
  88.         return dynamicClass;
  89.     }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement