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!

2
  • saw this ? tutorials.jenkov.com/java-reflection/… Commented Oct 26, 2012 at 4: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? Commented Oct 26, 2012 at 6:28

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

I think I answered a similar quetion before: Java ClassLoader Confusion
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.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.