Updating the CLASSPATH at runtime

Is there a way for a Java program to update the CLASSPATH environment variable?

You really shouldn't write your own class loader, if you're using JVM 1.2+. URLClassLoader works great for this purpose, and I've used it often to dynamically load classes. (Check out the link supplied by a2135 above--it allows you truly to add classes to the classpath.)
Another problem you might be having is how you are resolving the classes you want to add. For instance, I've a class name Sort, in package com.pe_gmbh.util. This :
    URLClassLoader loader = new URLClassLoader(new URL[] { new File("g:/_dev/OnlineApp/Kernel/classes/com/pe_gmbh/util/Sort.class").toURL() });
    Class cl = loader.loadClass("com.pe_gmbh.util.Sort");throws a ClassNotFoundException. I rather have to include the base class path :
    URLClassLoader loader = new URLClassLoader(new URL[] { new File("g:/_dev/OnlineApp/Kernel/classes/").toURL() });
    Class cl = loader.loadClass("com.pe_gmbh.util.Sort");The dynamic class load would then have two steps--you would have the user enter the new classpath, and (after scanning it), choose the fully-resolved class to use.
Hope this helps,
Walter Gildersleeve
Productivity Engineering, GmbH
Freiburg, Germany

Similar Messages

  • How to update the classpath on runtime

    My Application enables the user to select a directory. After this all *.class files in the directory and the subdirectories are listed. The User can now select a class to be initialised.
    This works well if the selected directory is in the Classpath. If the directory is not in the classpath, I tried to update the Classpath through
    System.setProperty("java.class.path",classpath).
    Well as I expected, this did not affect in any way. But how can I add the new directory to the classpath of the actual VM?
    Can anybody help please?

    Use a custom class loader. Examples have been posted in the forums. Search for them.

  • How do I set the classpath in runtime?

    How can i set the classpath in runtime?
    Im downloading my image files in the folder C:/Downloads
    I want to set this C:/Downloads as my classpath.
    I don want to set it at the initial stage, bcoz I may have to change the downloading directory D:/Selva.
    I want to access my */utils/New.gif* image available in the downloading directory by using getResource() method.

    java.net.URL urldir= new java.net.URL("file://C:/Downloads/");
    java.net.URL[] urlarr= new java.net.URL[1];
    urlarr[0]=urldir;
    java.net.URLClassLoader urlcl= new java.net.URLClassLoader(urlarr); +// Here I get the Error+
    url=urlcl.getResource("/lrp/utils/New.gif");
    *Error: java.security.AccessControlException: access denied (java.lang.RuntimePermission createClassLoader+                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to update the ItemRenderer at runtime..?

    Hi....
    am facing a hectic problem with ITemRenderes..
    My requirement is like i need to insert a Label and Image in
    each item of Horizontal List.
    For this i created a ArrayCollection with Lable and
    ImagePath. And assigning array as a Dataprovider to HorizontalList.
    and am attaching itemrenderer to it (which hold the lable and
    image).
    code:
    var data:ArrayCollection=new ArrayCollection({label:'A',
    path:'a.jpg'}, {label:'B', path:'b.jpg'}{label:'C', path:'c.jpg'});
    var hList:HorizontalList=new HorizontalList();
    hList.dataProvider=data;
    hList.itemRenderer=new ClassFactory(rendererObj);
    rendererObj holds the Lable Component and Image Componnet..
    Now the porblem is am trying to change the horizontal list at
    runtime. Like i want to change the lable of selected item in
    Horizontal list. Am able to update the arraycollection values. But
    its not getting effected in ItemRenderer.
    How to update the itemerenderer at runtime...?
    Thanks in Advance...
    Pratap

    Hi Pratap,
    I was playing with some sample code for this...
    Here is the main.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:Script>
    <![CDATA[
    import mx.utils.ArrayUtil;
    import mx.collections.ArrayCollection;
    import mx.collections.IViewCursor;
    import mx.controls.Alert;
    import mx.events.*;
    import mx.controls.dataGridClasses.DataGridListData;
    import mx.controls.listClasses.BaseListData;
    import mx.controls.HorizontalList;
    import mx.controls.dataGridClasses.DataGridColumn;
    import mx.containers.TitleWindow;
    [Bindable] private var myItemRenderer:ClassFactory;
    private function doit()
    myItemRenderer = new ClassFactory(rendererObj);
    var mydata:ArrayCollection=new
    ArrayCollection([{mylabel:'A', path:'a.jpg'}, {mylabel:'B',
    path:'b.jpg'},{mylabel:'C', path:'c.jpg'}]);
    var myList:HorizontalList = new HorizontalList();
    myList.dataProvider = mydata;
    this.addChild(myList);
    myList.itemRenderer=myItemRenderer;
    ]]>
    </mx:Script>
    <mx:Button x="204" y="191" label="Button"
    click="doit()"/>
    </mx:Application>
    Here is the rendererObj.mxml (component/itemrenderer)
    <?xml version="1.0" encoding="utf-8"?>
    <mx:VBox xmlns:mx="
    http://www.adobe.com/2006/mxml"
    width="110" height="76"
    implements="mx.core.IFactory,mx.controls.listClasses.IDropInListItemRenderer"
    backgroundColor="#BAB3B3" borderStyle="solid" borderThickness="3"
    borderColor="#000000">
    <mx:Script>
    <![CDATA[
    import mx.collections.IViewCursor;
    import mx.controls.listClasses.BaseListData;
    import mx.controls.Label;
    private var _listData:BaseListData;
    public function newInstance():*
    return new rendererObj();
    public function get listData() : BaseListData
    return _listData;
    public function set listData( value:BaseListData ) : void
    _listData = value;
    override public function set data(value:Object):void {
    if (value != null)
    var r:Label = new Label();
    r.text = value.mylabel;
    this.addChild(r);
    ]]>
    </mx:Script>
    </mx:VBox>
    See how that works..you press the button and the itemrenderer
    gets drawn into the horiz. list with the values from the
    arraycollection.
    I didnt implement the picture, but you get the idea on how to
    get
    the values into the hlist..
    hope this helps...

  • Dynamically adding jars to the classpath at runtime

    Hi All,
    I have a query regarding dynamically loading jars at runtime. I am developing an application that uses third party jars and there are a number of different versions that the utility is to support so I want to be able to load the jars relating to that specific version through selection on the gui. The jar files are the same name for all versions e.g.
    v1 has app1.jar
    and v2 has app2.jar
    I have these in separate folders called app1jars and app2jars. I have tried a number of classloader examples but always get a classnotfoundException. Any ideas? Thanks in advance for replies

    Hi,
    Sorry for being a bit vague. I have attached the code below that I was trying. Im confused about how to load the classes within each of the jars and use them do i have to use defineclass? AppSession is an interface.
    import java.util.*;
    import java.net.*;
    import java.sql.*;
    import com.app.AppSession;
    import com.app.AppWorker;
    import java.io.*;
    import java.lang.reflect.Method;
    public class JarTest {
        public static File[] getExternalJars()
        { String jarDirectory = "C:\\JarLoaderTest\\1.1jars";
          File jardir = new File(jarDirectory);
          File[] jarFiles = jardir.listFiles();
          return jarFiles;
        public static void main(String[] args) throws Exception {
         Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] {URL.class});
            addURL.setAccessible(true);
         File[] files = getExternalJars();
            ClassLoader cl = ClassLoader.getSystemClassLoader();
         for (int i = 0; i < files.length; i++) {
         URL url = files.toURL();
    System.out.println(url.toString());
         addURL.invoke(cl, new Object[] { url });
    cl.loadClass("AppSession").newInstance();
    cl.loadClass("AppWorker").newInstance();
    try
    { AppSession session = AppWorker.getConnection(username,password,port,server); // these are filled in with the actual details in my program
    catch(Exception e)

  • Dynamic update of the classpath

    Hi everybody !
    I'm working on an application that uses plugins and that is able to compile them from inside it. I need to update the classpath so that thae update is applied without restarting the application.
    For the moment I'm working like this:
    I catch the classpath:
    string path = System.getProperty(java.class.path)
    And then modify it:
    path = path + adds;
    System.setProperty(java.class.path,path);
    When I print the new classpath it seems that the modifications are applied but the compilation of the plugin show that it can't compile it because of not founding a class (tha is in a jar that is in the new classpath --> I'm sure of it the error don't come from that side). So I come to the conclusion that the classpath is not really updated ...
    Can someone confirm my conclusions or not ... or give me a way to the solution please ...
    Thx in advance !

    the compiler i'm using is part of the application and is using exactly the same environment ...
    and the changes are visible !!! : using System.getProperty and System.setProperty and printing the new classpath shows me that the classpath has been changed. But still it seems that the compiler don't look in the new libraries I've just put in the classpath

  • Set Classpath at runtime

    Hi everybody! I'm using NetBeans IDE 3.6 and I want to change the classpath at runtime. I�ve tried to make:
    set classpath="C:\Documents and Settings\Koening\Mis documentos\Proyectos";but it doesn�t recognize that sentence. If anybody knows how to change it at runtime please answer me.
    Thanks for the replies!!!

    I assume you were talking about a .bat file as you're writing that more or less in .bat format. The main problem if that's the case, is that you're not supposed to put quotes around the value:
    set classpath=C:\Documents and Settings\Koening\Mis documentos\Proyectos
    Actually changing the classpath at "runtime" (i.e., after the JVM is started) is more involved, and normally requires writing a launcher class which does nothing but create a URLClassLoader with the appropriate URLs, fetch the real main class from the new classloader, and executes its main method.

  • Get a ClassLoader determined at runtime into the classpath

    The class MyClass is dertermined at runtime and loaded from an URLClassLoader, which can not be in the original classpath.
    An objectInputStream is deserializing classes from that type, but it throws an exception and can not resolve that class, because it isn't in the classpath.
    Because the URLClassLoader is a JarFile, it is easy to iterate to them, but trying to do loadClass for each of them didn't enable the objectInputStream to recognize them.
    Some ideas where to create bytestreams from my class and extend a classloader to load those, but is there no easier way to get a classloader into the classpath or a single class into the list of classes of the classpath?

    I think that the main problem is that the ObjectInputStream cannot find the proper ClassLoader when deserializing.
    I have never tried it, but I think what needs to be done is to set the ContextClassLoader property of the thread that is doing the deserialization.
    Something like this:
    ClassLoader cl = new URLClassLoader(....);
    Thread t = Thread.currentThread();
    t.setContextClassLoader(cl);
    ObjectInputStream ois = new ObjectInputStream(....);
    Object o = ois.readObject();
    .

  • TS3694 I'm running XP. After downloading the latest itunes update i get a "Runtime error" and can't start itunes. Help?

    I'm running XP. After downloading the latest itunes update i get a "Runtime error" and can't start itunes. Help?

    iTunes 11.1.4 for Windows- Unable to install or open - MSVCR80 issue
    Solving MSVCR80 issue and Windows iTunes install issues.
    Thanks to user turingtest2 for this solution.
    Solving MSVCR80 issue and Windows iTunes install issues.
    If the above doesn’t do the trick entirely, then use the instructions in the following as it applies to the version of Windows you are using:
    HT1925: Removing and Reinstalling iTunes for Windows XP
    HT1923: Removing and reinstalling iTunes for Windows Vista, Windows 7, or Windows 8
    You may be required to boot into safe mode to complete the folder deletion process.

  • Just updated the lion os x, and now when I try to use my optus dongle, it comes up with the message saying that it won't work because Java Runtime needs to be installed.  Help?

    just updated the lion os x, and now when I try to use my optus dongle, it comes up with the message saying that it won't work because Java Runtime needs to be installed.  Help?

    Have you run Software Update.  You have Java already installed, but it needs to be updated.

  • Update the JSpinner/SpinnerDateModel at runtime.

    I'm having trouble updating the the value of of JSpinner field at runtime. The scenario is;
    Once the application is started the default system date/time is set on my JSpinner field. If I visit my page that contains the said Date (JSpinner) feild, it will show the time the system was started. But I always want to display the current date/time, at the time I visit the page, in the JSpinner Date field.
    The hierarchy of the code is;
    JPanel1 (base class)
    --- JPanel2
    --- JTabbedPane (consists of a couple of tabs, one of which is Jpanel3)
    --- Jpanel3 (different class by itself, which contains the desired JSpinner Date field)
    In JPanel3 I have implemented JSpinner as;
        public JSpinner getDateSpinnerField ()
            SpinnerDateModel dateModel= new SpinnerDateModel();
            dateModel.setCalendarField( Calendar.MONTH );
            JSpinner spinner= new JSpinner( dateModel);
            JSpinner.DateEditor dateEditor = new JSpinner.DateEditor( spinner, "MM/dd/yyyy HH:mm:ss" );
            dateEditor .getTextField().setEditable( false );
            spinner.setEditor( dateEditor );
            fromSpinner.addChangeListener( new javax.swing.event.ChangeListener() {
                public void stateChanged ( javax.swing.event.ChangeEvent e )
                    JSpinner jSpinner = (JSpinner)e.getSource();
                    SpinnerDateModel spinnerDateModel = (SpinnerDateModel)jSpinner.getModel();
                    setDateValue( spinnerDateModel.getDate() );
            return spinner;
        }Let me know if I need to paste the code as well and/or if any one needs any clarifications.
    thanks

    No, the the setDateValue() is for a different purpose here. It's just a setter and getter which holds the date value whenever user is modifying it. Lets not get diverted from the issue at hand.
    Also I have added a ChangeListener event on my tabbed pane, as implemneted below;
           <JTabbedPane>.addChangeListener( new javax.swing.event.ChangeListener() {
                    public void stateChanged ( javax.swing.event.ChangeEvent e )
                        int tabPosition = ( (JTabbedPane)e.getSource() ).getSelectedIndex();
                        JTabbedPane pane = (JTabbedPane)e.getSource();
                        if ( tabPosition == 1 ) {
                            System.out.println( "tabPosition: " + tabPosition );
                            Jpanel3 panel = ( Jpanel3 )pane.getSelectedComponent();
                            final JSpinner spinner = panel.getFromSpinnerField();
                            DateEditor editor = ( (DateEditor)spinner.getEditor() );
                            final SpinnerDateModel dateModel = editor.getModel();
                            dateModel.setValue( new Date() );
                            System.out.println("Value1: {"+dateModel.getValue()+"}");
                            try {
                                editor.commitEdit();
                                editor.repaint();
                                editor.revalidate();
                            catch ( ParseException pe ) {
                                System.out.println( "Exception" );
                                pe.printStackTrace();
                            SwingUtilities.invokeLater( new Runnable() {
                                public void run() {
                                    //spinner.invalidate();
                                    spinner.repaint();                       
                                    spinner.revalidate();
                                    System.out.println("Value2: {"+dateModel.getValue()+"}");
    But the date in the JSpinner feild doesn't get updated.
    thanks
    Edited by: javanuts on Mar 12, 2008 3:39 PM

  • [svn] 3839: Update the channel url to reflect the change in the runtime channel

    Revision: 3839
    Author: [email protected]
    Date: 2008-10-23 07:42:37 -0700 (Thu, 23 Oct 2008)
    Log Message:
    Update the channel url to reflect the change in the runtime channel
    Modified Paths:
    blazeds/branches/3.0.x/qa/apps/qa-manual/ajax/messaging/TextMessageRuntimeDest.html

    Many ways to do this. The easiest is to have a method in one of your classes that reads the data from the database and creates all the proper structure under a RootNode and then returns that RootNode.
    Whenever you want to refresh the tree, just call that method to recreate the root node (and all the underlying structure/nodes) and then re-set the root node of your tree model using the setRoot() method. That will cause it to refresh the display given the new root node.
    Once you have that working, you can get fancier and make it more efficient (only updating/firing events for the nodes that actually changed, etc).

  • [svn:bz-trunk] 15259: Update the blazeds-core Eclipse project . classpath to point to the new jgroups jar

    Revision: 15259
    Revision: 15259
    Author:   [email protected]
    Date:     2010-04-07 10:23:37 -0700 (Wed, 07 Apr 2010)
    Log Message:
    Update the blazeds-core Eclipse project .classpath to point to the new jgroups jar
    Modified Paths:
        blazeds/trunk/development/eclipse/projects/java/blazeds-core/.classpath

    Revision: 15259
    Revision: 15259
    Author:   [email protected]
    Date:     2010-04-07 10:23:37 -0700 (Wed, 07 Apr 2010)
    Log Message:
    Update the blazeds-core Eclipse project .classpath to point to the new jgroups jar
    Modified Paths:
        blazeds/trunk/development/eclipse/projects/java/blazeds-core/.classpath

  • HT1926 I updated the Itunes on my computer and it begin having problems. I tryed a new installation and there is a message saying an application has made an attempt to load C runtime library incorrectly. What shoul I do?

    I updated the Itunes on my computer and it begin having problems. I tryed a new installation and there is a message saying an application has made an attempt to load C runtime library incorrectly. What shoul I do?

    Hello rvalle3,
    The following article can help get iTunes updated and running again.
    iTunes 11.1.4 for Windows: Unable to install or open
    http://support.apple.com/kb/TS5376
    Cheers,
    Allen

  • Setting the CLASSPATH from the JVM by a class

    Hy experts
    I have an application thats searching a jar file and have to access classes from this jar file.
    There are two ways to do this:
    1.
    Loading the jar file byte by byte and create the classes to load them into memory. This is the hard way.
    2.
    Setting the CLASSPATH variable in the running program! Thats the easy way! May how does it works?
    Is there any possiblity to set the classpath in a running application or only in the shell?
    Thanks for help
    konrad

    the classpath is readin when you run the JVM ie issue the 'java' command, the environment cant be altered to update a new classpath. However, why not just put the files you wish to load at runtime within the current classpath you've setup. If you use the System.loadLibrary(), you should be able to pick up the classes you wish to readin at run time via this approach.
    good luck
    rob

Maybe you are looking for