0

I'm trying to load a class from a JAR file using reflection. This JAR file has a class that implements an Interface that is in a different JAR file. The JAR file that contains the interface is known by the project, since it is in its build path. This JAR file is also in two folders of JBoss 6, which are "client" and "common/lib".

The problem happens when I try to load the class dynamically to create an object, using the loadClass method of the class java.net.URLClassLoader. An ClassNotFoundException is thrown with regards to the interface that is shared by both the project and the JAR file. I'm obtaining the ClassLoader through the following method:

public static ClassLoader getClassLoader(final String fileName) {
    final File file = new File(fileName);
    URL url;
    ClassLoader classLoader = null;
    try {
        url = file.toURL();
        final URL[] urls = new URL[]{url};
        classLoader = new URLClassLoader(urls);

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return classLoader;
}

I have to load the class using this ClassLoader because the class is the File variable, which contains a reference to the JAR, which is not in JBoss.

Do I have to include the JAR with the Interface in a different folder of JBoss?

  • how do you get your instance of URLClassLoader? Did you try: java.lang.Thread.getContextClassLoader().loadClass()? – Tomasz Krzyżak Jul 21 '12 at 19:38
  • I tried to to this way also, but the class is not in the current thread, it is in the JAR file. I edited the question to provide more information. – José Alexandre Jul 22 '12 at 10:23

1 Answers1

0

You can only refer to classes that are in the Jboss classpath. So if the jar is not loaded by jboss there is no way you load it.

Tomer
  • 17,787
  • 15
  • 78
  • 137
  • I have already tried to include the JAR with the interface in the classpath of my EJB project, but it didn't work. I can instantiate objects of the JAR with interfaces in my project, but when I try to load the other JAR that has an implementation of this interface, the exception occurs. The most strange is that it runs correctly in one machine, but not on the others. I've already tried to copy both JBoss and Eclipse to the other one, but it still doesn't work. – José Alexandre Jul 22 '12 at 16:12
  • look here it might help you: http://stackoverflow.com/questions/219585/setting-multiple-jars-in-java-classpath – Tomer Jul 22 '12 at 16:15
  • also check this one: http://stackoverflow.com/questions/60764/how-should-i-load-jars-dynamically-at-runtime – Tomer Jul 22 '12 at 16:16
  • Thanks! The solutions that worked was passing as a paramenter the parentClassLoader. URLClassLoader child = new URLClassLoader (myJar.toURL(), this.getClass().getClassLoader()); – José Alexandre Jul 23 '12 at 09:34