Class MemoryClassLoader

All Implemented Interfaces:
Closeable, AutoCloseable

public class MemoryClassLoader extends URLClassLoader
An URLClassLoader that maintains an updatable cache of class files (as byte[] arrays) in memory from which classes may be loaded.

The internal cache of classes is initially empty. Binary class files may be added (or removed) via putClass(), and retrieved via getClass(). The byte[] arrays passed to and from these methods are copied to ensure immutability.

Classes defined by this loader are assigned URLs that look like memory:/com.example.MyClass.

This class is thread safe and parallel capable.

  • Field Details

  • Constructor Details

    • MemoryClassLoader

      public MemoryClassLoader()
      Default constructor.

      Uses the current thread's context loader as the parent loader.

    • MemoryClassLoader

      public MemoryClassLoader(ClassLoader parent)
      Constructor.
      Parameters:
      parent - parent class loader, possibly null
  • Method Details

    • putClass

      public void putClass(String className, byte[] classbytes)
      Add a class to this loader, making it available for class resolution.

      If an existing class already exists under className, it will be replaced. The classbytes array is copied to ensure immutability.

      If classbytes is null, any existing class will be removed.

      Parameters:
      className - Java class name
      classbytes - Java class file data
      Throws:
      IllegalArgumentException - if either parameter is null
    • getClass

      public byte[] getClass(String className)
      Get the class from this loader that was previously added via putClass(), if any.

      The returned array is a copy to ensure immutability.

      Parameters:
      className - Java class name
      Returns:
      class file previously added under the name className, or null if none exists
    • addURL

      public void addURL(URL url)
      Overrides:
      addURL in class URLClassLoader
    • findClass

      protected Class<?> findClass(String className) throws ClassNotFoundException
      Overrides:
      findClass in class URLClassLoader
      Throws:
      ClassNotFoundException
    • findResource

      public URL findResource(String resourceName)
      Overrides:
      findResource in class URLClassLoader
    • findResources

      public Enumeration<URL> findResources(String resourceName) throws IOException
      Overrides:
      findResources in class URLClassLoader
      Throws:
      IOException