Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JBoss 7: how to dynamically load jars

I am using JBoss 7 (dependency loading was changed in this version). My war-application uploads to server jars and need to use classes inside of them, but it gets ClassNotFoundException. So I can't find a way to add jar-dependencies to modules dynamically - MANIFEST.MF, jboss-deployment-structure.xml are static way of doing this.

like image 652
Rage Avatar asked Jan 03 '12 16:01

Rage


1 Answers

Just rephrasing the question to make sure I it correctly;

You want to be able to upload an arbitrary jar file to the server and then use the contained classes/resources in the JVM? Without restarting the JVM and/or editing your configuration ofcourse.

If that's the case, then you should load the jar into a classloader (chaining your current classloader if needed) and then load the class from there.

Assuming you store the jar-file physically on the server you could for example do something like:

public static Class<?> loadClass(String className, String jarFileLocation)
        throws MalformedURLException, ClassNotFoundException {
    URL jarUrl = new File(jarFileLocation).toURI().toURL();
    ClassLoader classLoader = new URLClassLoader(new URL[] {jarUrl }, MyClass.class.getClassLoader());
    return classLoader.loadClass(className);
}

public static Object executeMethodOndClass(String methodName, Class<?>[] parameterTypes, 
                                                Object[] parameters, String className, String jarFileLocation)
        throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException,
        NoSuchMethodException, InvocationTargetException {
    Class<?> loadedClass = loadClass(className, jarFileLocation);
    Method method = loadedClass.getMethod(methodName, parameterTypes);
    Object instance = loadedClass.newInstance();
    return method.invoke(instance, parameters);
}

Ps. this is crude code, I didn't even compile or test it; it should work, but nothing more then that and there is the chance I overlooked something or made a typo ;-)

Pps. allowing custom jar files to be uploaded and classes from it to be executed does bring a number of (security) risks with it.

like image 159
Barre Dijkstra Avatar answered Oct 16 '22 16:10

Barre Dijkstra