0

I want to implement PriorityClassLoader which can do following:

  • It accepts default ClassLoader instance as a constructor parameter
  • It has addURL method which work like addURL in URLClassLoader, but for each new URL it set the priority.

When the class should be loaded, loader first will try to load it with default classloader, if not - from the provided URLs according to the priority. Is there any ready solutions?

PS - my original problem was following - I wanted to add URL to the system classloader, but it began to fail on the duplicate classes in system classloader and remote JAR.

skayred
  • 10,603
  • 10
  • 52
  • 94
  • I'd rather unify jar versions or use something along the lines [OSGI](http://en.wikipedia.org/wiki/OSGi) – ssedano Dec 12 '13 at 14:15

2 Answers2

1

I've accidentally found this interesting library called JCL, and I've done it like this:

JarClassLoader jcl = new JarClassLoader();
jcl.add(new URL("hive://" + pageURL.getHost() + ":" + pageURL.getPort() + "/" + pageURL.getApplicationName() + "/origJar.jar"));

jcl.getSystemLoader().setOrder(1);
jcl.getThreadLoader().setOrder(2);
jcl.getCurrentLoader().setOrder(3);
jcl.getParentLoader().setOrder(4);
jcl.getLocalLoader().setOrder(5);

Thread.currentThread().setContextClassLoader(jcl);
skayred
  • 10,603
  • 10
  • 52
  • 94
0

To answer the question, I never heard of any ready made solution, but it could be done by some custom classloader, this is a simplified example from this blog post:

public class ExampleFactory {
  public static IExample newInstance() {
    URLClassLoader tmp =
      new URLClassLoader(new URL[] {getClassPath()}) {
        public Class loadClass(String name) {
          if ("example.Example".equals(name))
            return findClass(name);
          return super.loadClass(name);
        }
      };

    return (IExample)
      tmp.loadClass("example.Example").newInstance();
  }
}

For the original problem, did you try to put your libraries in the endorsed directory? This is a JDK standard mechanism that allows to add libraries at the level of the JVM bootstrap classloader.

Depending on your server there would be other alternatives where to place the classes. If none of this helps then it's better to give more info on the original problem.

Community
  • 1
  • 1
Angular University
  • 42,341
  • 15
  • 74
  • 81