0
public class ClassScanner
{
  // scan extraClasspath for specific classes
  public List<Class<?>> scanClasspathForClass(String scanCriteria)
  {
    ...
  }

  public static Class<?> reloadClass(Class<?> clazz, ClassLoader clazzLoader)
  {
    // Question: how to reload a loaded class (ClassScanner in this example) with a different arbitrary ClassLoader?
  }

  // an example of how reloadClass() would be used
  // in real case, this function would be in different class
  public List<Class<?>> scan(URL[] extraClasspath)
  {
    URLClassLoader urlClazzLoader = new URLClassLoader(extraClasspath, null);
    Class<?> newClass = reloadClass(ClassScanner.class, urlClazzLoader);
    return ((ClassScanner) newClass.newInstance()).scanClasspathForClass();
  }
}

Above code demonstrates the question and why it is a question. I need to implement reloadClass(). I wonder if there is a reliable solution in Java 1.6. One useful reference would be Find where java class is loaded from.

Thanks for help!

Community
  • 1
  • 1
Reci
  • 4,099
  • 3
  • 37
  • 42
  • saw this ? http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html#example – Nishant Oct 26 '12 at 04:10
  • Thanks. Saw that. Problem is, first the class could come from anywhere. I doubt `ClassLoader.getResource()` or `Class.getProtectionDomain().getCodeSource().getLocation()` are reliable. Second, if I may ask for simple solution without defining my ClassLoader? – Reci Oct 26 '12 at 06:28

1 Answers1

1

Found myself the answer from http://www2.sys-con.com/itsg/virtualcd/java/archives/0808/chaudhri/index.html.

Basically what I need is to make one ClassLoader A to share its namespace with another ClassLoader B. The way I found to achieve this is to use the ClassLoader parent-delegation model. Here, ClassLoader A is the parent ClassLoader.

public List<Class<?>> scan(URL[] extraClasspath) throws Exception
{
  URLClassLoader urlClazzLoader = new URLClassLoader(extraClasspath, ClassScanner.class.getClassLoader());
  return urlClazzLoader.loadClass(ClassScanner.getName()).newInstance();
}
Reci
  • 4,099
  • 3
  • 37
  • 42
  • I think I answered a similar quetion before: [Java ClassLoader Confusion](http://stackoverflow.com/a/10990094/697630) – Edwin Dalorzo Oct 27 '12 at 03:39
  • Thanks for the reference. However, in my case, all I need is to make two classes share a same namespace so that when they reference to some singleton object (such as FooBar.class), they use the same memory pointer. Parent ClassLoader solves the problem. – Reci Oct 29 '12 at 18:48
  • Is this going to work? If the ClassScanner has been already loaded through the parent classloader, then the extraClasspath will be irrelevant and the class will be returned from the parent classloader, won't it? – Filip Majernik May 04 '21 at 07:47