How to dynamically load jar files - limiting scope to that thread

Dynamically loading jar files has been discussed a lot. I have read a quite a few posts, articles, and demo code for doing just that. However, I have yet to find a solution to my problem. Most people modify their system class loader and are happy. I have done that and was happy for a time. Occasionally, you will see reference to an application server or tomcat or some other large project that have successfully been able to load and unload jar files, allow for dynamic deployment of code, etc. However, I have not been able to achieve similar success; And my problem is much less complicated.
I have an application that executes a thread to send a given file/message to a standard JMS Server Queue. Depending on the parameters selected by the user, this thread may need to communicate with one of a number of JMS Servers, ie. JBoss, WebLogic, EAServer, Glassfish, etc. All of which can be done with the same code, but each needs to load their own flavor of JMS Client Jar files. In this instance, spawning a separate JVM for each communication would work from a classloader perspective. However, I need to keep it in the family and run under the same JVM, albeit each JMS Server Connection will be created and maintained in separate Threads.
I am close, I am doing the following...
1. Creating a new URLClassLoader in the run() method of each thread.
2. Set this threads contextClassLoader to the new URLClassLoader.
3. Load the javax.jms.JMSException class with the URLClassLoader.loadClass() method.
4. Create an initialContext object within this thread.
Note: I read that the initialContext and subsequent conext lookup calls would use the Thread�s
contextClassLoader for finding/loading classes.
5. Perform context.lookup calls for a connectionFactory and Queue name.
6. Create JMS Connection, etc. Send Message.
Most of this seems to work. However, I am still getting a NoClassDefFoundError exception for the javax.jms.JMSException class ( Note step #3 - tried to cure unsuccessfully).
If I include one of the JMS Client jar files ( ie wljmsclient.jar for weblogic ) in the classpath then it works for all the different JMS Servers, but I do not have confidence that each of the providers implemented these classes that now resolve the same way. It may work for now, but, I believe I am just lucky.
Can anyone shine some light on this for me and all the others who have wanted to dynamically load classes/jar files on a per Thread basis?

Thanks to everyone - I got it working!
First, BenSchulz' s dumpClassLoader() method helped me to visualize the classLoader hierarchy. I am still not completely sure I understand why my initial class was always found by the systemClassLoader, but knowning that - was the step I needed to find the solution.
Second, kdgregory suggested that I use a "glue class". I thought that I already was using a "glue class" because I did not have any JMSClient specific classes exposed to the rest of the application. They were all handled by my QueueAdmin class. However...
The real problem turned out to be that my two isolating classes (the parent "MessageSender", and the child "QueueAdmin") were contained within the same jar file that was included in the classpath. This meant that no matter what I did the classes were loaded by the systemClassLoader. Isolating them in classes was just the first step. I had to remove them from my jar file and create another jar file just for those JMSClient specific classes. Then this jar file was only included int custom classLoader that I created when I wanted to instantiate a JMSClient session.
I had to create an interface in the primary jar file that could be loaded by the systemClassLoader to provide the stubs for the individual methods that I needed to call in the MessageSender/QueueAdmin Classes. These JMSClient specific classes had to implement the interface so as to provide a relationship between the systemClassLoader classes and the custom classLoader classes.
Finally, when I loaded and instantiated the JMSClient specific classes with the custom classLoader I had to cast them to the interface class in order to make the method calls necessary to send the messages to the individual JMS Servers.
psuedu code/concept ....
Primary Jar File   -  Included in ClassPath                                                      
Class<?> cls = ClassLoader.loadClass( "JMSClient.MessageSender" )
JMSClientInterface jmsClient = (JMSClientInterface) cls.newInstance()                            
jmsClient.sendMessage()                                                                      
JMSClient Jar File  -  Loaded by Custom ClassLoader Only
MessageSender impliments Primary.JMSClientInterface{
    sendMessage() {
        Class<?> cls=ClassLoader.loadClass( "JMSClient.QueueAdmin" )
        QueueAdmin queueAdmin=(QueueAdmin) cls.newInstance()
        queueAdmin.JMSClientSpecificMethod()
    }

Similar Messages

  • Dynamically loading jar files

    Hi
    In my application I need to dynamically create objects of types specified by string which is passed as parameter. I am able to do this if the class is inside the same jar. But I need to load the class from any jar name specified. How do i go about doing this? Is there a way to dynamically loading jar files?

    It's easy. You use [url http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLClassLoader.html]URLClassLoader:String jarPath = ...;
    String className = ...;
    URLClassLoader ucl = new URLClassLoader(new URL[] { new File(jarPath).toURL() });
    Class cls = Class.forName(className, true, ucl);
    ...Regards

  • Dynamically load jar file

    Hi,
    I've got an applet (used in a website) which must internally load a jar (the jarname and mainclassname are stored in the database).
    with a lot of jars (more than 10) and slow-internet users of my applet, it is not an option to add all the jars to the archive-parameter within the applet:
    <APPLET
         CODE="my.mainClass.class"
         width="800"
         height="600"
         archive = "MyMainJar.jar,someOther.jar, another.jar, andAgain.jar, lastExample.jar"
         codebase="/javaclasses"
    >
    So, adding all the jars is not an option, because if a class of the last jar (in this example: lastExample.jar) is needed, all the other jars must be loaded first.
    I have tried it with a classloader, to load the jar, but i've got an AccessControlException:
    java.security.AccessControlException: access denied (java.lang.RuntimePermission createClassLoader)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkCreateClassLoader(Unknown Source)
         at java.lang.ClassLoader.<init>(Unknown Source)
    The question is: how can I dynamically (in an applet) open a jar, and create an instance of a class in that jar?
    I searched the internet, but google can't help me out.
    Regards,
    Thijs

    It shouldn't be that difficult; all the stuff you need to build jars is in java.util.jar.*.
    Essentially it's back to combining the jars you need into one big one, give a different name to each of the different combinations you might need. You'd probably have the composite jars stored, but when one was requested it would check the dates of the component jars and rebuild if needed.

  • Load jar file into Oracle db 10.1.0.2.0.

    Hi,
    I am trying to create a Java Stored procedure that is dependent on some other classes. The java source doesn't compile since it cannot find the imported libs.
    How can I load jar files into the database so I can get my java source to compile?
    I have heard of dbms_java.loadjava procedure, but not very clear on how to use it.
    Please let me know how I can load the jar files in to the db.
    Thanks,
    -- DR.

    http://oraclesvca2.oracle.com/docs/cd/B12037_01/java.101/b12021/dbms_jav.htm

  • How can i put Jar Files in Java Runtime.?

    HI,
    how can i put jar files in JRE so that they are accessible every where.? is there some way.?
    Regards,
    AA

    Closest you could get to this I think is to explode all your jars into the same parent directory. Then if you put that directory on the classpath, you should be able to access all classes in all jar files

  • How to load jar files from remote location

    Hi all,
    I am trying to load jar files from remote server, from a servlet which is running on OC4j.
    For doing this,First I am getting ClassLoader by using ClassLoader.getSystemClassLoader() and then type casting it to URLClassLoader.
    But by doing it I am getting ClassCastException,because oc4j returns oracle.classloader.PolicyClassLoader instead of java.net.ClassLoader.
    Appreciate if anyone can tell me how to load remote jar files using oracle.classloader.PolicyClassLoader .
    Thanks
    Harish

    Hi,
    I suppose you know about this, but just in case.
    I have used jnpl to load jar files from remote location.
    Rowan

  • How to load jar file in oracle 9i???

    Hi Friends,
    Can you help me, how to load jar file oracle 9i? I have to tried to load in 10g using loadjava command but it's not working in oracle 9i because the loadjava batch file itself is not there in oralce 9i.
    Is there any other way then pls let me know.
    - Hiren Modi

    Hi,
    I have oracle version : Release 2 (9.2.0.1.0) for Windows. I have tried to execute the loadjava command from SQL prompt but its giving as below.
    H:\>loadjava
    The system cannot find the path specified.
    Do you know why its giving error like this. I have checked in dir : C:\oracle\ora92\bin but loadjava executable file is not there in it.
    - Hiren Modi

  • How to list the JAR files loaded into the Oracle Database ?

    How to list the JAR files loaded into the Oracle Database ?

    From 11.1 onwards, the below two views are available to identify the jar files loaded into the Database.
    JAVAJAR$
    JAVAJAROBJECTS$
    By querying the JAVAJAR$ view you can know information about the JAR files loaded into the Database and using JAVAJAROBJECTS$ view you can find all the java objects associated with the given JAR file.
    These views are populated everytime you use LOADJAVA with "-jarsasdbobjects" option to load your custom java classes.
    But unfortunately this feature is available only from 11.1 onwards and there is no clear workaround for above in 10.2 or earlier.

  • How to load jar file using SQL Developer

    Dear All,
    I need urgent help to load mytest.jar to the database using SQL Developer. I am able to load individual java classes to the database using SQL developers, but i could not load JAR files. Please help me any one know how to do this using SQL Developer.
    Thanks and Regards
    John p

    I don't think that's possible, so load it through the OS with the loadjava utility.
    Have fun,
    K.

  • Load jar file

    Hi
    I use EBS r12, i try to load jar file, i put it in $OA_JAVA/oracle/apps/fnd/jar and run adautocfg.sh, but the application not see the jar file?
    Is there any solution for that?
    Thanks

    Read from application developers guide for ebs developers about how to register jar files in oracle ebs. Also read these,
    Java and JAR in Oracle Apps
    http://www.exforsys.com/tutorials/oracle-apps/registering-new-forms-in-oracle-apps-11i.html
    http://www.aboutoracleapps.com/2009/01/how-to-register-shell-script-as.html

  • How to package other jar files into one jar?

    How to package other jar files into one jar? How can i get the class in the inner jar file?

    Generally not a good idea. The Java runtime won't be able to load classes from those "inner" jars, you'd have to write your own classloader to do that. It's not a brilliant idea, generally, anyway, since the point of having lots of jars is to keep your application modular. Bundling them all together like that means you have to re-deploy the whole thing to fix, for instance, one small bug in one small library
    If you really want to do this, there's an Eclipse plugin called FatJar, but I urge you to consider whether you really want to do it first.

  • Loading jar files at execution time via URLClassLoader

    Hello�All,
    I'm�making�a�Java�SQL�Client.�I�have�practicaly�all�basic�work�done,�now�I'm�trying�to�improve�it.
    One�thing�I�want�it�to�do�is�to�allow�the�user�to�specify�new�drivers�and�to�use�them�to�make�new�connections.�To�do�this�I�have�this�class:�
    public�class�DriverFinder�extends�URLClassLoader{
    ����private�JarFile�jarFile�=�null;
    ����
    ����private�Vector�drivers�=�new�Vector();
    ����
    ����public�DriverFinder(String�jarName)�throws�Exception{
    ��������super(new�URL[]{�new�URL("jar",�"",�"file:"�+�new�File(jarName).getAbsolutePath()�+"!/")�},�ClassLoader.getSystemClassLoader());
    ��������jarFile�=�new�JarFile(new�File(jarName));
    ��������
    ��������/*
    ��������System.out.println("-->"�+�System.getProperty("java.class.path"));
    ��������System.setProperty("java.class.path",�System.getProperty("java.class.path")+File.pathSeparator+jarName);
    ��������System.out.println("-->"�+�System.getProperty("java.class.path"));
    ��������*/
    ��������
    ��������Enumeration�enumeration�=�jarFile.entries();
    ��������while(enumeration.hasMoreElements()){
    ������������String�className�=�((ZipEntry)enumeration.nextElement()).getName();
    ������������if(className.endsWith(".class")){
    ����������������className�=�className.substring(0,�className.length()-6);
    ����������������if(className.indexOf("Driver")!=-1)System.out.println(className);
    ����������������
    ����������������try{
    ��������������������Class�classe�=�loadClass(className,�true);
    ��������������������Class[]�interfaces�=�classe.getInterfaces();
    ��������������������for(int�i=0;�i<interfaces.length;�i++){
    ������������������������if(interfaces.getName().equals("java.sql.Driver")){
    ����������������������������drivers.add(classe);
    ������������������������}
    ��������������������}
    ��������������������Class�superclasse�=�classe.getSuperclass();
    ��������������������interfaces�=�superclasse.getInterfaces();
    ��������������������for(int�i=0;�i<interfaces.length;�i++){
    ������������������������if(interfaces[i].getName().equals("java.sql.Driver")){
    ����������������������������drivers.add(classe);
    ������������������������}
    ��������������������}
    ����������������}catch(NoClassDefFoundError�e){
    ����������������}catch(Exception�e){}
    ������������}
    ��������}
    ����}
    ����
    ����public�Enumeration�getDrivers(){
    ��������return�drivers.elements();
    ����}
    ����
    ����public�String�getJarFileName(){
    ��������return�jarFile.getName();
    ����}
    ����
    ����public�static�void�main(String[]�args)�throws�Exception{
    ��������DriverFinder�df�=�new�DriverFinder("D:/Classes/db2java.zip");
    ��������System.out.println("jar:�"�+�df.getJarFileName());
    ��������Enumeration�enumeration�=�df.getDrivers();
    ��������while(enumeration.hasMoreElements()){
    ������������Class�classe�=�(Class)enumeration.nextElement();
    ������������System.out.println(classe.getName());
    ��������}
    ����}
    It�loads�a�jar�and�searches�it�looking�for�drivers�(classes�implementing�directly�or�indirectly�interface�java.sql.Driver)�At�the�end�of�the�execution�I�have�found�all�drivers�in�the�jar�file.
    The�main�application�loads�jar�files�from�an�XML�file�and�instantiates�one�DriverFinder�for�each�jar�file.�The�problem�is�at�execution�time,�it�finds�the�drivers�and�i�think�loads�it�by�issuing�this�statement�(Class�classe�=�loadClass(className,�true);),�but�what�i�think�is�not�what�is�happening...�the�execution�of�my�code�throws�this�exception
    java.lang.ClassNotFoundException:�com.ibm.as400.access.AS400JDBCDriver
    ��������at�java.net.URLClassLoader$1.run(URLClassLoader.java:198)
    ��������at�java.security.AccessController.doPrivileged(Native�Method)
    ��������at�java.net.URLClassLoader.findClass(URLClassLoader.java:186)
    ��������at�java.lang.ClassLoader.loadClass(ClassLoader.java:299)
    ��������at�sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:265)
    ��������at�java.lang.ClassLoader.loadClass(ClassLoader.java:255)
    ��������at�java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
    ��������at�java.lang.Class.forName0(Native�Method)
    ��������at�java.lang.Class.forName(Class.java:140)
    ��������at�com.marmots.database.DB.<init>(DB.java:44)
    ��������at�com.marmots.dbreplicator.DBReplicatorConfigHelper.carregaConfiguracio(DBReplicatorConfigHelper.java:296)
    ��������at�com.marmots.dbreplicator.DBReplicatorConfigHelper.<init>(DBReplicatorConfigHelper.java:74)
    ��������at�com.marmots.dbreplicator.DBReplicatorAdmin.<init>(DBReplicatorAdmin.java:115)
    ��������at�com.marmots.dbreplicator.DBReplicatorAdmin.main(DBReplicatorAdmin.java:93)
    Driver�file�is�not�in�the�classpath�!!!�
    I�have�tried�also�(as�you�can�see�in�comented�lines)�to�update�System�property�java.class.path�by�adding�the�path�to�the�jar�but�neither...
    I'm�sure�I'm�making�a/some�mistake/s...�can�you�help�me?
    Thanks�in�advice,
    (if�there�is�some�incorrect�word�or�expression�excuse�me)

    Sorry i have tried to format the code, but it has changed   to �... sorry read this one...
    Hello All,
    I'm making a Java SQL Client. I have practicaly all basic work done, now I'm trying to improve it.
    One thing I want it to do is to allow the user to specify new drivers and to use them to make new connections. To do this I have this class:
    public class DriverFinder extends URLClassLoader{
    private JarFile jarFile = null;
    private Vector drivers = new Vector();
    public DriverFinder(String jarName) throws Exception{
    super(new URL[]{ new URL("jar", "", "file:" + new File(jarName).getAbsolutePath() +"!/") }, ClassLoader.getSystemClassLoader());
    jarFile = new JarFile(new File(jarName));
    System.out.println("-->" + System.getProperty("java.class.path"));
    System.setProperty("java.class.path", System.getProperty("java.class.path")+File.pathSeparator+jarName);
    System.out.println("-->" + System.getProperty("java.class.path"));
    Enumeration enumeration = jarFile.entries();
    while(enumeration.hasMoreElements()){
    String className = ((ZipEntry)enumeration.nextElement()).getName();
    if(className.endsWith(".class")){
    className = className.substring(0, className.length()-6);
    if(className.indexOf("Driver")!=-1)System.out.println(className);
    try{
    Class classe = loadClass(className, true);
    Class[] interfaces = classe.getInterfaces();
    for(int i=0; i<interfaces.length; i++){
    if(interfaces.getName().equals("java.sql.Driver")){
    drivers.add(classe);
    Class superclasse = classe.getSuperclass();
    interfaces = superclasse.getInterfaces();
    for(int i=0; i<interfaces.length; i++){
    if(interfaces[i].getName().equals("java.sql.Driver")){
    drivers.add(classe);
    }catch(NoClassDefFoundError e){
    }catch(Exception e){}
    public Enumeration getDrivers(){
    return drivers.elements();
    public String getJarFileName(){
    return jarFile.getName();
    public static void main(String[] args) throws Exception{
    DriverFinder df = new DriverFinder("D:/Classes/db2java.zip");
    System.out.println("jar: " + df.getJarFileName());
    Enumeration enumeration = df.getDrivers();
    while(enumeration.hasMoreElements()){
    Class classe = (Class)enumeration.nextElement();
    System.out.println(classe.getName());
    It loads a jar and searches it looking for drivers (classes implementing directly or indirectly interface java.sql.Driver) At the end of the execution I have found all drivers in the jar file.
    The main application loads jar files from an XML file and instantiates one DriverFinder for each jar file. The problem is at execution time, it finds the drivers and i think loads it by issuing this statement (Class classe = loadClass(className, true);), but what i think is not what is happening... the execution of my code throws this exception
    java.lang.ClassNotFoundException: com.ibm.as400.access.AS400JDBCDriver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:198)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:186)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:265)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:140)
    at com.marmots.database.DB.<init>(DB.java:44)
    at com.marmots.dbreplicator.DBReplicatorConfigHelper.carregaConfiguracio(DBReplicatorConfigHelper.java:296)
    at com.marmots.dbreplicator.DBReplicatorConfigHelper.<init>(DBReplicatorConfigHelper.java:74)
    at com.marmots.dbreplicator.DBReplicatorAdmin.<init>(DBReplicatorAdmin.java:115)
    at com.marmots.dbreplicator.DBReplicatorAdmin.main(DBReplicatorAdmin.java:93)
    Driver file is not in the classpath !!!
    I have tried also (as you can see in comented lines) to update System property java.class.path by adding the path to the jar but neither...
    I'm sure I'm making a/some mistake/s... can you help me?
    Thanks in advice,
    (if there is some incorrect word or expression excuse me)

  • How to make a jar file downloadable with IE

    hello,
    I just bought a website:
    http://www.frozenfountain.net/
    and I put a jar file on it called Logo.jar
    Using Mozilla, the jar file downloads as expected, but with Internet Explorer, it tries to download it as .zip file.
    How do I get it to download as a .jar file with IE?
    thanks

    Just post a link to the Jar. Mozilla will download
    it as a jar. Windows will download it as a zip.
    Only one link. No problem, really. ;-)There is a problem. People who arent as good with computers as you are won't know how to run the jar file after downloading with IE.
    At school, I told someone to download the file, which they did with IE. It downloaded to desktop as a zip. They extracted and were left with a bunch of .class files.
    On a sidenote, how do you draw text with a gradient?

  • How to call a jar file from oracle forms (6i)

    Hi,
    I'm working with oracle 6i. I want to know that how to call a .jar file from forms menu. when I use HOST('<path>\test.jar') it is working in 'Client Server' any way. but the problem is I use application server in order to run my form. so my form is in the server and I run the form via clients web browser. in that case above solution will not work. if any body knows how to overcome this problem please reply.
    thanks.
    duminda

    I created a bean area and set the class name as implementation class. within that java bean class I called to a bat file which consists of the execution command of the jar file ( because i don't know how to call .jar file from my bean class directly).
    then i tried to run it in application server. its still not running.
    can you tell me what i have to do within my bean class? or can you suggest any solution?
    thank you.

  • How to call a .jar file from a java bean?

    any body knows how to call a .jar file from a java bean?

    Crosspost!
    http://forum.java.sun.com/thread.jspa?messageID=4349619

Maybe you are looking for

  • Database Error: DBD::Oracle::db do failed: ORA-04030: out of process memory

    Hi I have a stored procedure that uses the XMLQuery function (SELECT XMLQuery( '......' RETURNING CONTENT) FROM dual; ) to extract data from 3 different tables and store the xml file in XML DB. This store procedure was running fine for a long time un

  • HT1688 iPhone 5 baked, any hope or is it hopeless?

    I have a 16g  iPhone 5.  I've been having horrible battery life.  A full battery lasts me litteraly 6hrs.  I try to keep all settings to minimum as well as follow all the tips everyone suggests regarding battery convservation/consumption.  Still noth

  • How do I re-enable the Administrator's account in Windows Server 2008?

    I can not log onto my server because my administrator account is disabled. But i know the password of server. The server not join to domain. i dare not try any way, i want to know the solution for make sure because this server run many services. Plea

  • How to add timer in Report

    In my z report I have two different BDC transaction. I want After 1st execution of BDC and before execution of 2nd BDC I want to add a 1 minute time. So how can I add that timer between BDC. Thanks Kaushik

  • Running java 2 on pre OS X

    I am taking a class in Java 1.3 at the local university. I am running mac OS 9 on my machine at home. Everywhere I look people say that it is not possible to run anything about java 1.1.8 on pre OS X machines. Apple's site had this to say: Q: Is ther