Dynamic class loading problem using unknown JAR archive and directory names

I read the following article, which enlightened me a lot:
Ted Neward: Understanding Class.forName().
However, it took me some while to understand that my problem is the other way around:
I know the name of the class, I know the name of the method,
but my program/JVM does not know where to load the classes from.
Shortly, my problem is that the server engine that I am writing
uses two different versions of the same library.
So I am trying out the following solution:
My program is named TestClassPathMain.java
Assume the two libraries are named JAR1.jar and JAR2.jar
and the class/instance method that should
be exposed to TestClassPathMain.java by them is named
TestClass1.testMethod().
As long as I was depending on just one library,
I put JAR1.jar in the classpath before starting java,
and I was happy for a while.
At the moment I got the need to use another version of
TestClass1.testMethod() packaged in JAR2.jar,
a call would always access JAR1.jar's
TestClass1.testMethod().
I then decided to remove JAR1.jar from the classpath,
and programmatically define two separate ClassLoaders, one for use
with JAR1.jar and the other for use with JAR2.jar.
However, the problem is only partly solved.
Please refer to the enclosed code for details.
(The code in the JAR1.jar/JAR2.jar is extremely simple,
it just tells (by hardcoding) the name of the jar it is packaged in
and instantiates another class packaged in the same jar using
the "new" operator and calls a method on it. I don't enclose it.)
The TestClassPathMain.java/UC1.java/UC2.java code suite was
successfully compiled with an arbitrary of JAR1 or JAR2 in the classpath,
however removed from the classpath at runtime.
(I know that this could have been done (more elegantly...?) by producing an Interface,
but I think the main problem principle is still untouched by this potential lack of elegancy(?))
1) This problem should not be unknown to you experts out there,
how is it generally and/or most elegantly solved?
The "*** UC2: Variant 2" is the solution I would like best, had it only worked.
2) And why arent "*** UC2: Variant 2" and
"*** static UC2: Variant 2" working,
while "*** Main: Variant 2" is?
3) And a mal-apropos:
Why can't I catch the NoClassDefFoundError?
The output:
*** Main: Variant 1 JAR 1 ***:
Entering TestClass1.testMethod() packaged in JAR1.jar
About to instantiate TestClass2 with the new operator
About to call TestClass2.testMethod()
Entering TestClass2.testMethod() packaged in JAR1.jar
*** Main: Variant 1 JAR 2 ***:
Entering TestClass1.testMethod() packaged in JAR2.jar
About to instantiate TestClass2 with the new operator
About to call TestClass2.testMethod()
Entering TestClass2.testMethod() packaged in JAR2.jar
*** Main: Variant 2 JAR 1 ***:
Entering TestClass1.testMethod() packaged in JAR1.jar
About to instantiate TestClass2 with the new operator
About to call TestClass2.testMethod()
Entering TestClass2.testMethod() packaged in JAR1.jar
*** Main: Variant 2 JAR 2 ***:
Entering TestClass1.testMethod() packaged in JAR2.jar
About to instantiate TestClass2 with the new operator
About to call TestClass2.testMethod()
Entering TestClass2.testMethod() packaged in JAR2.jar
*** UC1: Variant 1 JAR 1 ***:
Entering TestClass1.testMethod() packaged in JAR1.jar
About to instantiate TestClass2 with the new operator
About to call TestClass2.testMethod()
Entering TestClass2.testMethod() packaged in JAR1.jar
*** UC1: Variant 1 JAR 2 ***:
Entering TestClass1.testMethod() packaged in JAR2.jar
About to instantiate TestClass2 with the new operator
About to call TestClass2.testMethod()
Entering TestClass2.testMethod() packaged in JAR2.jar
*** static UC2: Variant 2 JAR 1 ***:
Exception in thread "main" java.lang.NoClassDefFoundError: TestClass1
        at UC2.runFromJarVariant2_static(UC2.java:56)
        at TestClassPathMain.main(TestClassPathMain.java:52)
TestClassPathMain.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class TestClassPathMain {
    public static void main(final String args[]) throws MalformedURLException, ClassNotFoundException, InstantiationException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
            // Commented out because I cannot catch the NoClassDefFoundError.
            // Why?
            try {
                final TestClass1 testClass1 = new TestClass1();
                System.out.println(
                    "\nThe class TestClass1 is of some unexplicable reason available." +
                    "\nFor the purpose of the test, it shouldn't have been!" +
                    "\nExiting");
                System.exit(1);
            } catch (NoClassDefFoundError e) {
                System.out.println("\nPositively confirmed that the class TestClass1 is not available:\n" + e);
                System.out.println("\n\nREADY FOR THE TEST: ...");
            // Works fine
            System.out.println("\n*** Main: Variant 1 JAR 1 ***:");
            runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
            System.out.println("\n*** Main: Variant 1 JAR 2 ***:");
            runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
            // Works fine
            System.out.println("\n*** Main: Variant 2 JAR 1 ***:");
            runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
            System.out.println("\n*** Main: Variant 2 JAR 2 ***:");
            runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
            // Works fine
            final UC1 uc1 = new UC1();
            System.out.println("\n*** UC1: Variant 1 JAR 1 ***:");
            uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
            System.out.println("\n*** UC1: Variant 1 JAR 2 ***:");
            uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
            // Crashes
            System.out.println("\n*** static UC2: Variant 2 JAR 1 ***:");
            UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
            System.out.println("\n*** static UC2: Variant 2 JAR 2 ***:");
            UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
            // Crashes
            final UC2 uc2 = new UC2();
            System.out.println("\n*** UC2: Variant 2 JAR 1 ***:");
            uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
            System.out.println("\n*** UC2: Variant 2 JAR 2 ***:");
            uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
    private static void runFromJarVariant1(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
        final URL url = new URL(jarFileURL);
        final URLClassLoader cl =
            new URLClassLoader(new URL[]{url},
                               Thread.currentThread().getContextClassLoader());
        final Class clazz = cl.loadClass("TestClass1");
        final Object testClass1 = clazz.newInstance();
        final Method testMethod1 = clazz.getMethod("testMethod", null);
        testMethod1.invoke(testClass1, null);
    private static void runFromJarVariant2(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
        final URL url = new URL(jarFileURL);
        final URLClassLoader cl =
            new URLClassLoader(new URL[]{url},
                               Thread.currentThread().getContextClassLoader());
        final Class clazz = cl.loadClass("TestClass1");
        final TestClass1 testClass1 = new TestClass1();
        testClass1.testMethod();
UC1.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class UC1 {
    public void runFromJarVariant1(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
        final URL url = new URL(jarFileURL);
        final URLClassLoader cl =
            new URLClassLoader(new URL[]{url},
                               Thread.currentThread().getContextClassLoader());
        final Class clazz = cl.loadClass("TestClass1");
        final Object testClass1 = clazz.newInstance();
        final Method testMethod1 = clazz.getMethod("testMethod", null);
        testMethod1.invoke(testClass1, null);
UC2.java
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class UC2 {
    public void runFromJarVariant2(final String jarFileURL)
    throws MalformedURLException,
           ClassNotFoundException,
           InstantiationException,
           IllegalArgumentException,
           IllegalAccessException,
           InvocationTargetException,
           SecurityException,
           NoSuchMethodException {
        final URL url = new URL(jarFileURL);
        final URLClassLoader cl =
            new URLClassLoader(new URL[]{url},
                               Thread.currentThread().getContextClassLoader());
        final Class clazz = cl.loadClass("TestClass1");
        final TestClass1 testClass1 = new TestClass1();
        testClass1.testMethod();
     * Identic to the "runFromJarVariant2" method,
     * except that it is static
    public static void runFromJarVariant2_static(final String jarFileURL)
    throws MalformedURLException,
           ClassNotFoundException,
           InstantiationException,
           IllegalArgumentException,
           IllegalAccessException,
           InvocationTargetException,
           SecurityException,
           NoSuchMethodException {
        final URL url = new URL(jarFileURL);
        final URLClassLoader cl =
            new URLClassLoader(new URL[]{url},
                               Thread.currentThread().getContextClassLoader());
        final Class clazz = cl.loadClass("TestClass1");
        final TestClass1 testClass1 = new TestClass1();
        testClass1.testMethod();
}

2. i need to load the class to the same JVM (i.e. to
the same environment) of the current running
aplication, so that when the loaded class is run, it
would be able to invoke methods on it!!!
ClassLoader(s) do this. Try the URLClassLoader.
(I was talking about relatively esoteric "security"
issues when I mentioned the stuff about Class objects
"scope".) You might use the URLClassLoader kind of
like this.
Pseudo-code follows:
// setup the class loader
URL[] urls = new URL[1];
urls[0] = new URL("/path/to/dynamic/classes");
URLClassLoader ucl = new URLClassLoader(urls);
// load a class & use make an object with the default constructor
Object tmp = ucl.loadClass("dynamic.class.name").newInstance();
// Cast the object to a know interface so that you can use it.
// This may be used to further determine which interface to cast
// the class to. Or it may simply be the interface to which all
// dynamic classes have to conform in your program.
InterfaceImplementedByDynamicClass loadedObj =
    (InterfaceImplementedByDynamicClass)tmp;It's really not as hard as it sounds, just write a little test of
this and you will see how it works.

Similar Messages

  • Dynamic class load problem..

    Hello all,
    I am rather new to this concept of creating class loaders.
    I started on a simple test and landed into a problem right away. I have a Java class file stuffed away somewhere on m machine (at a location not on my CLASSPATH) . I just want to load that class dynamically. Here is my humble code :
    import java.io.*;
    public class DynamicClassLoadTest extends ClassLoader {
         String classFileName;
         String pathToClassFile;
         public static void main(String[] args) {
              try {
                   if(args.length != 2) {
                        System.out.println("Usage : java DynamicClassLoadTest <path to class file> <name of class file>");
                        System.exit(0);
                   System.out.println("MISSION: To dynamically load class " + args[1] + " from path : " + args[0]);
                   DynamicClassLoadTest dcl = new DynamicClassLoadTest();
                   Class cls = dcl.loadClass(args[1], args[0], true);
              catch(Exception e) {
                   System.out.println("Mission failed with error : " + e);
                   e.printStackTrace();
         public Class loadClass(String name, String path, boolean resolve)
              throws ClassNotFoundException
              this.pathToClassFile=path;
              this.classFileName= name;
              return (loadClass(name, resolve));
         public Class loadClass(String name, boolean resolve)
              throws ClassNotFoundException
              try {
                   File f = new File(pathToClassFile, name + ".class");
                   if(!f.exists())
                        throw new ClassNotFoundException("Specified class not found");
                   FileInputStream fis = new FileInputStream(f);
                   long fileSize = f.length();
                   System.out.println("Size of class file = " + fileSize);
                   byte[] classBytes = new byte[(int) fileSize];
                   int r = fis.read(classBytes);
                   System.out.println("Bytes read is " + r + " and file size is " + fileSize + " and byte array length is " + classBytes.length);
                   Class c = defineClass(name, classBytes, 0, classBytes.length);
                   System.out.println("CLASS created..");
                   return c;
              catch(Exception e) {
                   throw new ClassNotFoundException(e.getMessage());
    When I execute as :
    java DynamicClassLoadTest /Users/user1 JustTest
    the below is printed on execution :
    MISSION: To dynamically load class JustTest from path : /Users/user1
    Size of class file = 421
    Bytes read is 421 and file size is 421 and byte array length is 421
    Exception in thread "main" java.lang.NoClassDefFoundError: java/lang/Object
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:431)
    at DynamicClassLoadTest.loadClass(DynamicClassLoadTest.java:56)
    at DynamicClassLoadTest.loadClass(DynamicClassLoadTest.java:33)
    at DynamicClassLoadTest.main(DynamicClassLoadTest.java:18)
    The class file has apparently been read fine - then why is this java/lang/object reference ?
    Any tips would be of huge help.
    Thanks.

    An extension to this.
    What should I do when I have to load a jar dynamically ? I manage to load the main class of the jar successfully. But what about classes in the jar which are invoked by this class. Say we have case as below :
    JustAJar.jar contains :
    sh-2.05a$ jar tvf JustAJar.jar
    0 Fri May 23 14:41:14 PDT 2003 META-INF/
    70 Fri May 23 14:41:14 PDT 2003 META-INF/MANIFEST.MF
    567 Fri May 23 14:40:52 PDT 2003 InvokeTheNext.class
    475 Fri May 23 14:40:52 PDT 2003 InvokeMe.class
    Now, InvokeMe is the class I instantiate :
    public class InvokeMe {
    public static void main(String[] args) {
    System.out.println("Welcome to InvokeMe");
    InvokeTheNext itn = new InvokeTheNext("InvokeMe");
    InvokeTheNext is :
    public class InvokeTheNext {
    public InvokeTheNext(String str) {
    System.out.println("Welcome to InvokeTheNext");
    System.out.println("Recd ur msg " + str);
    Now I manage to define and resolve the class InvokeMe, but when the class is invoked, the foll error is thrown :
    Resolved class with name InvokeMe successfully
    Welcome to InvokeMe
    Mission failed with error : java.lang.reflect.InvocationTargetException
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at InvokeForClassLoad.main(InvokeForClassLoad.java:46)
    Caused by: java.lang.NoClassDefFoundError: InvokeTheNext
         at InvokeMe.main(InvokeMe.java:4)
    I tried loading the entire jar file into the CLASSPATH dynamically (using System.setProperty) but that doesnt help. Any inputs please ?
    Thanks.

  • Dynamic Class Loading and Stubs

    How Dynamic Class Loading is used on Java RMI, since stubs are generated on clients using Reflection API?
    I was reading Dynamic code downloading using JavaTM RMI (http://java.sun.com/javase/6/docs/technotes/guides/rmi/codebase.html), it seems to be out of date.
    For example, "The client requests the class definition from the codebase. The codebase the client uses is the URL that was annotated to the stub instance when the stub class was loaded by the registry. Back in step 1, the annotated stub for the exported object was then registered with the Java RMI registry bound to a name."

    "Enhancements in J2SETM 5.0
    Dynamic Generation of Stub Classes
    This release adds support for the dynamic generation of stub classes at runtime, obviating the need to use the Java(tm) Remote Method Invocation (Java RMI) stub compiler, rmic, to pregenerate stub classes for remote objects. *Note that rmic must still be used to pregenerate stub classes for remote objects that need to support clients running on _earlier versions_.*
    When an application exports a remote object (using the constructors or static exportObject methods(1) of the classes java.rmi.server.UnicastRemoteObject or java.rmi.activation.Activatable) and a pregenerated stub class for the remote object's class cannot be loaded, the remote object's stub will be a java.lang.reflect.Proxy instance (whose class is dynamically generated) with a java.rmi.server.RemoteObjectInvocationHandler as its invocation handler.
    An existing application can be deployed to use dynamically generated stub classes unconditionally (that is, whether or not pregenerated stub classes exist) by setting the system property java.rmi.server.ignoreStubClasses to "true". If this property is set to "true", pregenerated stub classes are never used.
    Notes:
    * If a remote object has pre-5.0 clients, that remote object should use a stub class pregenerated with rmic or the client will get an ClassNotFoundException deserializing the remote object's stub. Pre-5.0 clients will not be able to load an instance of a dynamically generated stub class, because such a class contains an instance of RemoteObjectInvocationHandler, which was not available prior to this release.
    * Prior to the J2SE 5.0 release, exporting a remote object would throw a java.rmi.StubNotFoundException if the pregenerated stub class for the remote object's class could not be loaded. With the added support for dynamically generated stub classes, exporting a remote object that has no pregenerated stub class will silently succeed instead. A user deploying a server application to support pre-5.0 clients must still make sure to pregenerate stub classes for the server's remote object classes, even though missing stub classes are no longer reported at export time. Such errors will instead be reported to a pre-5.0 client when it deserializes a dynamically generated stub class.
    (1) The static method UnicastRemoteObject.exportObject(Remote) is declared to return java.rmi.server.RemoteStub and therefore cannot be used to export a remote object to use a dynamically generated stub class for its stub. An instance of a dynamically generated stub class is a java.lang.reflect.Proxy instance which is not assignable to RemoteStub."
    http://java.sun.com/j2se/1.5.0/docs/guide/rmi/relnotes.html

  • Is Dynamic Class Loading(RMI) Possible in EJB?

    In Java RMI,it allows dynamic class loading,that is when the stub and interface class files are modified by the server,the client side can download the updated stub and inteface classes.
    As the remote interface of EJB extends Javax.ejb.EJBObject which in turn extends java.rmi.remote.Also the Home interface of EJB extends
    javax.ejb.EJBHome which also extends java.rmi.remote.
    Therefore I wonder if EJB also supports dynamic class
    loading as RMI does.If yes,how to do so?Is it the responsibility of the Application Servers and transparent
    to client? If No,then is this a defect in EJB??
    Thank you very much in advance!!
    John

    This would be done by the container and is transparent to the client. Most app servers support "hot deploy" where you can deploy beans while the server is running. This requires dynamic class loading.

  • Why do we use only dynamic class loading for JDBC drivers

    Hi,
    My JDBC experience is that we always use dynamic class loader for drivers.
    If we have a well defined package from a vendor, why do we use this dynamic class loading feature for drivers??

    chandunitw wrote:
    Hi,
    My JDBC experience is that we always use dynamic class loader for drivers.
    If we have a well defined package from a vendor, why do we use this dynamic class loading feature for drivers??Oftentimes, the driver class name is set in a configuration file, not in code. So the thing which processes the configuration file has no idea ahead of time which driver or drivers it will support, so it is not coded specifically for any. So it loads the driver by reflection, since it is given the class name as a string it can use with the reflection API.

  • Dynamic class loading when CODEBASE is unreachable. A bug?

    Let us suppose that we have a large-scale distributed application with ca. 1000 participants communicating via RMI and utilizing dynamic class loading. As we all know, a HTTP code server must be available for this purpose in order to provide dynamically downloaded code, usually the communication proxy code of remote objects. In a real-world scenario, the HTTP server will never be 100% available, so that we will have cases that a Java process will not be able to download the necessary Java classes, causing the RMI communication to fail with a ClassNotFoundException or similar exception. In such a case, a robust application would perform some recovery activities and retry the remote call. Eventually, the HTTP server becomes available again and the distributed system recovers automatically. This seems to work fine with J2SE 1.4.2_10, but not with 1.4.2_11 and newer versions. Considering Java 5, the Update 9 exhibits the same problem.
    For tracking down the problem, I've written a simple distributed test application, consisting of a client and a server. A server listens on a port, and sends a MarshalledObject to the client. The code of the MarshalledObject is annotated with the value of the "java.rmi.server.codebase" system property. The annotation contains an URL of the JAR file containing the code of the original object. The client connects to the server, reads data form the socket and unmarshalls the original object. This is basically the same procedure as when objects are accross the wire as arguments/return values/exceptions by the RMI/JRMP engine. This procedure is repeated forever in the loop. Due to the fact that the client's CLASSPATH doesn't contain the code of the original object, this code should dynamically be loaded from the HTTP server using the appropriate annotation provided by the server.
    If we start the client while the HTTP server is down, the client will keep generating the ClassNotFoundException over and over again, as expected. So far, so good. If we now start the HTTP server while the client is still running, we will observe different behaviors, depending on the version of the client's JVM:
    1. In J2SE 1.4.2_10, the client will download the code from the HTTP server and successfully unmarshal the original object sent by the server. ClassNotFoundExceptions will not be generated again.
    2. In J2SE 1.4.2_11, 1.4.2_12 and 1.4.2_13 as well as in J2SE 5.0 Update 9, the client will continue generating ClassNotFoundExceptions. Analysis of the HTTP server's access log shows that there were no attempts to download the JAR file required for unmarshaling the object sent by the server.
    It seems that in the newer JVM versions the RMI engine remembers URLs which have failed and does not attempt to access them anymore. Althogh this may have some advantages considering the overall network load, the dynamical class loading becomes practically useless in productive large distributed systems. The very first attempt to load the codebase of the communication peer must succeed, otherwise the whole process must be restarted for the communication to work, which is a very expensive (and for most customers unacceptable) operation in terms of preformance and resources usage.
    Should this be seen as a bug or a feature of the JVM? What do you think?
    Regards,
    Miran
    Here is the code to reproduce:
    Server code
    package server;
    import java.net.*;
    import java.rmi.*;
    import java.io.*;
    public class Server implements Serializable {
      private int value = 42;
      public Server() {
      public String toString() {
        return "The Answer is " + value;
      public static void main( String[] args ) {
        if( args.length!=1 ) {
          System.out.println( "Usage: server.Server <port>" );
          System.exit( 1 );
        try {
          MarshalledObject data = new MarshalledObject( new Server() );
          int port = Integer.parseInt( args[0] );
          ServerSocket serverSocket = new ServerSocket( port );
          System.out.println( "Accepting connections..." );
          while( true ) {
            Socket s = serverSocket.accept();
            new Thread( new SocketHandler( s, data ) ).start();
        } catch( Exception ex ) {
          ex.printStackTrace();
        System.exit( 0 );
      public static class SocketHandler implements Runnable {
        private Socket s;
        private Serializable data;
        public SocketHandler( Socket s, Serializable data ) {
          this.s = s;
          this.data = data;
        public void run() {
          try {
            OutputStream os = s.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream( os );
            oos.writeObject( data );
            oos.close();
            os.close();
            s.close();
            System.out.println( "Serving socket succeeded" );
          } catch( Exception ex ) {
            System.out.println( "Serving socket failed" );
            ex.printStackTrace();
    Client code
    package client;
    import java.rmi.*;
    import java.net.*;
    import java.io.*;
    public class Client {
      public static void main( String[] args ) {
        if( args.length!=1 ) {
          System.out.println( "Usage: client.Client <port>" );
          System.exit( 1 );
        try {
          if( System.getSecurityManager()==null ) {
            System.setSecurityManager( new RMISecurityManager() );
          int port = Integer.parseInt( args[0] );
          for( int i = 1; true; ++i ) {
            try {
              Socket s = new Socket( "localhost", port );
              InputStream is = s.getInputStream();
              ObjectInputStream ois = new ObjectInputStream( is );
              Object o = ois.readObject();
              ois.close();
              is.close();
              s.close();
              Object umo = ((MarshalledObject) o).get();
              System.out.println( i + ". Retreiving MarshalledObject succeeded: "
                                  + umo );
            } catch( Exception ex ) {
              System.out.println( i + ". Retreiving MarshalledObject failed" );
              ex.printStackTrace();
            System.out.println( i + ". Waiting for 10 sec" );
            Thread.sleep( 10000 );
        } catch( Exception ex ) {
          ex.printStackTrace();
        System.exit( 0 );
    Start command for the server
    java -cp server.jar -Djava.rmi.server.codebase="http://localhost/playground/server.jar" server.Server 33933
    Start command for the client
    java -cp client.jar -Djava.security.policy=all.policy client.Client 33933
    The policy.all file should look as follows
    // All permissions
    grant {
       permission java.security.AllPermission;
    };The server.jar file should only contain the classes from the server package. This file should also be made accessible via HTTP (e.g. by using the Apache HTTP server).
    The client.jar file should only contain the classes from the client package.

    no body know about this??

  • Dynamic Class Loading with interface

    Hello
    I would appreciate any help on the following problem.
    I need to load all classes in a particular directory and its subdirectories (top directory is known but not in the classpath) which implement a predefined interface. At the moment I am using a lot of reflection to accomplish this and believe it can be avoided somehow using the fact that I know these classes have to implement a predefined interface.
    At the moment, I am searching through the directory and subdirectory, loading all names of classes into a vector using a custom URLClassloader, and then load all classes in the vector into modulecontainers to populate a defaultmutabletree which is displayed on the gui.
    I'm sure that knowing the interface means there's a more straightforward way.
    Thanks in advance.

    Finally i've found out myself, i've read some postings in this forum and put them all together, so that my webstart-application finally works the way i want...
    That was the topic:
    Downloading a jar-file and starting a class from this jar-file within a webstart application (dynamic class loading).
    I'll post my final solution for this problem, may be it would be useful in future for anyone else.
    //grant all permissions on the clientside
    Policy.setPolicy( new Policy() {
    public PermissionCollection getPermissions(CodeSource codesource) {
    Permissions perms = new Permissions();
    perms.add(new AllPermission());
    return(perms);
    public void refresh(){
    //get the current classloader
    ClassLoader cl = MyLoadedClass.class.getClassLoader();
    //create a new url-classloader while using the current classloader
    URL[] urls = new URL[1];
    File f = new File(new String(jarName));
    urls[0] = f.toURL();
    URLClassLoader ul = new URLClassLoader(urls, cl);
    //load a class from jarfile
    Class c = ul.loadClass(new String(className));
    //get an object from loaded class
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof KnownInterface){
    // Yep, lets call a method we know about. */
    KnownInterface client = (KnownInterface) o;
    client.doAnything();

  • Dynamic class loading with Webstart

    Hello !
    //within the jar-file at the webstart-directory
    public interface MyFrame{
    public void createFrame();
    //within the jar-file dynamically downloaded
    public class MyExtFrame extends JFrame implements MyFrame{
    String className = "MyExtFrame";
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    JarClassLoader jarLoader = new JarClassLoader (cl, jarFile));
    /* Load the class from the jar file and resolve it. */
    Class c = jarLoader.loadClass (className, true);
    /* Create an instance of the class.
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof MyFrame){
    // Yep, lets call a method we know about. */
    MyFrame client=(MyFrame) o;
    //call a class-method (here creates the whole gui-object at once)
    client.createFrame();
    This is the code i'm using and i've encountered following problem, if i put this code into an application without webstart, anything works fine, but with webstart i'll get a: java.lang.NoClassDefFoundError
    Then i've put the MyFrame-classes into the downloaded jar-file, but this won't work either, i'll get a ClassCastException.
    What do i have to do, to become it working ?
    Thanks for any conclusions and help.
    Michael

    Finally i've found out myself, i've read some postings in this forum and put them all together, so that my webstart-application finally works the way i want...
    That was the topic:
    Downloading a jar-file and starting a class from this jar-file within a webstart application (dynamic class loading).
    I'll post my final solution for this problem, may be it would be useful in future for anyone else.
    //grant all permissions on the clientside
    Policy.setPolicy( new Policy() {
    public PermissionCollection getPermissions(CodeSource codesource) {
    Permissions perms = new Permissions();
    perms.add(new AllPermission());
    return(perms);
    public void refresh(){
    //get the current classloader
    ClassLoader cl = MyLoadedClass.class.getClassLoader();
    //create a new url-classloader while using the current classloader
    URL[] urls = new URL[1];
    File f = new File(new String(jarName));
    urls[0] = f.toURL();
    URLClassLoader ul = new URLClassLoader(urls, cl);
    //load a class from jarfile
    Class c = ul.loadClass(new String(className));
    //get an object from loaded class
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof KnownInterface){
    // Yep, lets call a method we know about. */
    KnownInterface client = (KnownInterface) o;
    client.doAnything();

  • Dynamic Class Loading and Unloading

    I am trying to create a system where the class name and method name is
    picked up from a meta-data database and executed.
    This was accompanied using Dynamic Class loading. I tried to extend this to
    support versioning of meta-data. Here depending on the version of meta-data
    different libraries can be loaded and different implementations of object
    with the same name can be executed. This does not seem to work with Forte
    3.0.
    When the second Library is loaded the method execution does not work.
    (Even though the unload flag on the LoadLibrary is set)
    If the application is stopped and restarted pointing to the second library
    there is no problem. In a running application a dynamically loaded library
    does not seem to unload and reload a new library for the same class names.
    Has anyone tried sometime similar, is there a workaround for this type of
    problem.
    - Vivek

    I am trying to create a system where the class name and method name is
    picked up from a meta-data database and executed.
    This was accompanied using Dynamic Class loading. I tried to extend this to
    support versioning of meta-data. Here depending on the version of meta-data
    different libraries can be loaded and different implementations of object
    with the same name can be executed. This does not seem to work with Forte
    3.0.
    When the second Library is loaded the method execution does not work.
    (Even though the unload flag on the LoadLibrary is set)
    If the application is stopped and restarted pointing to the second library
    there is no problem. In a running application a dynamically loaded library
    does not seem to unload and reload a new library for the same class names.
    Has anyone tried sometime similar, is there a workaround for this type of
    problem.
    - Vivek

  • Dynamic class loading from String name

    Hello all,
    I have a question for dynamic class loading:
    If I have a String variable that represents a class name, how can i use it to make dynamically an object of the class tha the string variable represents?
    For example i have a string like this
    String classname="String";
    Using this i want to make a new String object .
    Can anyone tell me how can i do this(example plz)?

    I have worked out the code and this works fine:
    import java.lang.*;
    class dynamictestname{
         public dynamictestname() {
        public static Class test(String objname){
             try{
             Class theClass = Class.forName(objname);
                 return theClass;
            } catch (ClassNotFoundException e)
                throw new NoClassDefFoundError (e.getMessage());
         public static void main (String [] args){
              String classname="java.lang.String";
              Class thisClass=dynamictestname.test(classname);
              try{
              Object instance = thisClass.newInstance();
              }catch(InstantiationException e){
              }catch(IllegalAccessException ie){
    }The new problem i 've faced is that i can't instatiate a new object by the class i have created.I saw some examples with use of the java.lang.reflect but this class i used with user created classes which have methods that the user wants to run dynamically.
    I just want to make an object from the class and give it a value.
    For example if the object i have created with the
    Object instance = thisClass.newInstance();is an object of java.lang.String class
    how can i do something like this below dynamically from instance object :
    String x="TEST ";
    Thanks for the help..

  • Dynamic Class Loading (RMI)

    Hi,
    i have my rmi server, implementing objects,stubs and skeleton classes deployed in my Tomcat server and they are stored under the tomcat root folder.
    In anoather jvm iam trying to load the classes thru the below code.
    java -Djava.rmi.server.codebase=http://ssd8/tomcat-3.2.4/install_dir/webapps/ROOT/WEB-INF/rmicode stockMarketClient
    ssd8 is the hostname(machine) which contains all my rmi server files.
    and stockmarketclient is my rmi client.
    Iam getting the java.lang.noclassdeffound error.
    what may be the problem???
    Should i have the security policy file in the client machine.

    Please Do tell me if any of the following worked I'll be greatly obliged
    1) Try this
    java -Djava.rmi.server.codebase=http://servername/dir1/dir2/ RMIServer
    This / thing at the end of the URL is very important
    2) This is how I did it just Today
    Dynamic Class Loading Using RMI
         Server Side
    1) Main Interface
    2) Implementing Class
    3) Stub & Skel                    (RMI Server & Web Server)
    4) All Other Classes used by the Server
         Web Server Side
    1) Main Interface
    2) Stub & Skel                    (RMI Server & Web Server)
    3) All Other Classes (not Main Client Class)
         Client Side
    1) Main Interface
    2) Main Client Class
    3) Stubs
    4) Security Manager
         RUNNING
    SERVER
         java DataServerImpl
    CLIENT
         java DataClient xyz
    Note
    Make Calls as follows
    System.setSecurityManager(new LaxSecurityManager());
    DataServer server = (DataServer) Naming.lookup("rmi://localhost:1099/DataServer");
    Runnable r = (Runnable)server.getNewClass();
    r.run();
    DON'T make Calls as follows
    System.setSecurityManager(new LaxSecurityManager());
    DataServer server = (DataServer) Naming.lookup("rmi://localhost:1099/DataServer");
    NewClass obj = server.getNewClass();
    obj.run();
    if done as above provide the Class NewClass to the Client as well ( whole purpose defeated)
    Code
         // SecurityManager
    import java.rmi.*;
    import java.security.*;
    public class LaxSecurityManager extends RMISecurityManager
         // All Checks are routed through this method
         public void checkPermission(Permission p)
              // do nothing
         // Main Interface
    import java.rmi.*;
    public interface DataServer extends Remote
         public boolean login(String usr_name,char[] pass_wrd) throws RemoteException;
         public Object getNewClass() throws RemoteException;
         // Main Server
    import java.rmi.*;
    import java.rmi.server.*;
    import java.rmi.registry.*;
    public class DataServerImpl /*extends UnicastRemoteObject*/ implements DataServer
         static
              try
                   LocateRegistry.createRegistry(1099);
              catch(Exception e)
                   System.err.println("Static " + e);
         public boolean login(String usr_name,char[] pass_wd) throws RemoteException
              System.out.println("Welcome " + usr_name);
              if( pass_wd == null || pass_wd.length == 0 || pass_wd.length > 10 )
                   return false;
              return true;
         public Object getNewClass() throws RemoteException
              System.out.println("Returning New Class");
              return new NewClass();
         public DataServerImpl() throws RemoteException
              try
                   System.setProperty("java.rmi.server.codebase","http://localhost:8080/");
                   UnicastRemoteObject.exportObject(this);
                   Naming.rebind("DataServer",this);
              catch(java.net.MalformedURLException e)
                   System.err.println("DataServerImpl " + e);
                   return;
              System.out.println("Server Registered");
         public static void main(String[] args) throws Exception
              new DataServerImpl();
         // Class Moving Around the Network
    public class NewClass implements java.io.Serializable,Runnable
         int num;
         public void run()
              System.out.println("Start the Server with Number = " + num);
         public NewClass()
              num = (int)(Math.random()*1000);
         public String toString()
              return num + "";
         // Client
    import java.rmi.*;
    public class DataClient
         public static void main(String[] args) throws Exception
              System.setSecurityManager(new LaxSecurityManager());
              String pass = new String();
              if(args.length == 0)
                   System.err.println("usage: java DataClient PassWord");
                   System.exit(1);
              else
                   pass = args[0];
              DataServer server = (DataServer) Naming.lookup("rmi://localhost:1099/DataServer");
              Runnable r = (Runnable)server.getNewClass();
              r.run();
    All the Best

  • "Open-code" statements / dynamic class-loading

    Hi!
    I am using reflection to dynamically load classes in an application where the classes are read dynamically from a text-box (or a file) in a running Java-session. When a class is loaded, instances can be made. All this works fine.
    Now consider the following example:
    1. First a class Sample1 is loaded:
    public class Sample1 {
    public int i;
    Sample1() {
    i=5;
    2. I want to make an instance of Sample1 like:
    Sample1 s1=new Sample1();
    To use dynamic load, this "open-code" statement needs (?) to be put in a class Sample2. This works fine, and the method()-method can be invoked (using reflection):
    public class Sample2 {
    public Sample1 s1;
    public void method(String args[]) { 
    s1=new Sample1();
    System.out.println(s1.i);
    3. At last I want to refer (print) to s1.i (and again the code is wrapped in a class), but this doesn't work:
    public class Sample3 {
    public void method(String args[]) { 
    System.out.println(s1.i);
    The problem is how the statement:
    Sample1 s1=new Sample1();
    can be executed so that s1 can be referenced in the running Java-session.
    Any suggestions how to solve this design-problem? What I want to do is make "open-code" statements that can be referenced in the running Java-session.
    Regards,
    Jesper

    Typically, your 'open code statements' would be wrapped in a class that implements a suitable interface. If you wish to have state shared between your generated classes, then some form of common store (such as a Map) needs to be used to hold the state, and this made accessible to the implementations.
    eg:interface PluginMethod { void apply (Map state) ;}
    public class Sample2 implements PluginMethod {
      public void apply (Map state) {
         state.put("s1", new Sample1());
    public class Sample3 implements PluginMethod {
      public void apply (Map state) {
         System.out.println(((Sample1)state.get("s1")).i);
    }Alternatively, any of the normal methods of sharing state between objects can be used if closer coupling is desired. Dynamic class loading doen't really come into it- you use the same techniques as you normally do.
    Pete

  • Dynamic class loading failed, why?

    Hi there!
    We are using WebLogic 5.1 togehter with Apache1.3.22/Tomcat4.01. It all worked
    fine for about 2 month. All of a sudden, dynamic class loading refuses to work.
    From one day to the other I got the excpetion: javax.naming.CommunicationException.
    Root exception is weblogic.rmi.UnmarshalException: Unmarshalling return
    - with nested exception:
    [java.lang.ClassNotFoundException: class com.dsh.egb.aks.betrieb.ejbs.AnmeldenEJBHomeImpl_ServiceStub
    previously not found]
    Why does this happen? I can not remember having touched any properties.
    Please help,
    Heiner

    If you were relying on client network classloading stubs from WebLogic, you
    can test if it still works by pointing your browser to
    htpp://yourweblogic:7001/classes/com/dsh/egb/aks/betrieb/ejbs/AnmeldenEJBHomeImpl_ServiceStub.class
    Heiner Amthauer <[email protected]> wrote:
    Hi there!
    We are using WebLogic 5.1 togehter with Apache1.3.22/Tomcat4.01. It all worked
    fine for about 2 month. All of a sudden, dynamic class loading refuses to work.
    From one day to the other I got the excpetion: javax.naming.CommunicationException.
    Root exception is weblogic.rmi.UnmarshalException: Unmarshalling return
    - with nested exception:
    [java.lang.ClassNotFoundException: class com.dsh.egb.aks.betrieb.ejbs.AnmeldenEJBHomeImpl_ServiceStub
    previously not found]
    Why does this happen? I can not remember having touched any properties.
    Please help,
    Heiner--
    Dimitri

  • Dynamic class loading in J2ME

    Hi all,
    Couple of questions. Is dynamic class loading using classloaders supported in any, if not all versions of J2ME? I guess I should ask first, what exactly does J2ME cover? I see KVM, but do watches and PDA's, set top boxes, refrigerators and so forth all run the same J2ME JVM? Or are their "less feature full" versions? I was hoping the J2ME spec would be the "lowest common denominator" to program for, but I thought I read somewhere that small devices like watches may even have a "smaller" J2ME JVM or something, less capable. So can I write code for J2ME and it will run on all small devices like cell phones, pda's, and so forth? Or is there another J2ME version, perhaps small than J2ME.
    So, from what I have found so far, it appears dynamic class loading is done at startup from a DB (of sorts) as opposed to being able to dynamically find/load classes. If this is so, is there any way to support downloading and reloading new classes like you can with J2SE, such as the hot-swap feature of web servers? Does Class.forName() at least work in that you can "replace" a class with a new version, even if it is not able to have a separate classloader instance? My guess is that J2ME supports only a single classloader space, but I thought I read somewhere that Class.forName() is available. J2ME API shows it I believe, but I could be wrong.
    Any help on this topic would be appreciated.
    Thanks.

    Dynamic class loading is not available in most (if not all) J2ME profiles and configurations. Class.forName() is available (at least in the MID profile), but not to be used for dynamic class loading. It can be used when using device-specific APIs where you can try to load a class containing device specific methods (for example a class that works only on certain Nokia phones, and has methods playSound() and vibrate(), which are not available in MIDP), and if you catch a ClassNotFound exception you can load a class that doesn't use the device specific APIs and contains stubs of the methods, or you can disable certain features in you application that need those features. For an example implementation you can have a look at Nokia's Block Game example (available from their developer site - http://www.forum.nokia.com/main.html).
    As for your other more general questions about different JVM's and such, you should read all about the different configurations and profiles available in J2ME (plenty of information using in the J2ME link on this site).

  • Error adding package to class that is using a jar

    Hi,
    I have a class that is using a jar but I need it to be in a package so I can use it with JSP, but each time I put the package in the class I get some compile errors that the classes in the jar can't be found.
    Example:
    Compiling 1 source file to C:\Documents and Settings\ehasbunv\Mis documentos\proyecto\mex\cc\build\web\WEB-INF\classes
    C:\Documents and Settings\ehasbunv\Mis documentos\proyecto\mex\cc\src\java\tecno\Tecnomen.java:22: cannot find symbol
    symbol : class PP_OpenInterface
    location: class tecno.Tecnomen
    private PP_OpenInterface pp = null;
    C:\Documents and Settings\ehasbunv\Mis documentos\proyecto\mex\cc\src\java\tecno\Tecnomen.java:23: cannot find symbol
    symbol : class PP_OpenInterface_Factory
    location: class tecno.Tecnomen
         private PP_OpenInterface_Factory ppf     = null;
    C:\Documents and Settings\ehasbunv\Mis documentos\proyecto\mex\cc\src\java\tecno\Tecnomen.java:127: cannot find symbol
    symbol : class PP_exception
    location: class tecno.Tecnomen
    public int GenericRecharge (String Subid,int monto) throws PP_exception
    C:\Documents and Settings\ehasbunv\Mis documentos\proyecto\mex\cc\src\java\tecno\Tecnomen.java:79: cannot find symbol
    symbol : variable PP_OpenInterface_FactoryHelper
    location: class tecno.Tecnomen
    ppf = PP_OpenInterface_FactoryHelper.narrow(nsRef);
    C:\Documents and Settings\ehasbunv\Mis documentos\proyecto\mex\cc\src\java\tecno\Tecnomen.java:91: cannot find symbol
    symbol : class PP_exception
    location: class tecno.Tecnomen
    catch(PP_exception ex)
    C:\Documents and Settings\ehasbunv\Mis documentos\proyecto\mex\cc\src\java\tecno\Tecnomen.java:139: cannot find symbol
    symbol : class paramRecord
    location: class tecno.Tecnomen
    paramRecord pSeq [] = new paramRecord[] {
    C:\Documents and Settings\ehasbunv\Mis documentos\proyecto\mex\cc\src\java\tecno\Tecnomen.java:139: cannot find symbol
    symbol : class paramRecord
    location: class tecno.Tecnomen
    paramRecord pSeq [] = new paramRecord[] {
    C:\Documents and Settings\ehasbunv\Mis documentos\proyecto\mex\cc\src\java\tecno\Tecnomen.java:140: cannot find symbol
    symbol : class paramRecord
    location: class tecno.Tecnomen
    new paramRecord(0,subId),
    C:\Documents and Settings\ehasbunv\Mis documentos\proyecto\mex\cc\src\java\tecno\Tecnomen.java:141: cannot find symbol
    symbol : class paramRecord
    location: class tecno.Tecnomen
    new paramRecord(1,amount),

    Checking another file, the problem is that if I'm
    trying to use a class in the default package in
    another class and put a package name in the class
    then I can't use the default package. Is there any
    workaround?Nope. Get in the habit now of making ALL of your classes belong to packages. The "no-package" is only for creating 'toy' applications with no dependencies from other packaged classes.

Maybe you are looking for

  • Previewing video in iTunes for windows Crashes iTunes

    When I try to preview a video with iTunes on my Vista machine, I get the error message "iTunes has stopped working". Any idea how to fix this?

  • Where can I find a downloadable benchmark for the MacBook Pro?

    I have a 2013 MacBook Pro and a 2006 Mac Pro. I am thinking of dumping the Mac Pro and make my MacBook my one and only computer. I want to run a benchmark on each system to see what I am trading off with this plan. Where can I find a downloadable ben

  • How to write ABAP Workflow test script

    Hi Please any body tell me what is the workflow test script. And how to write. Please if any body have the documentation please share wd me

  • 10G RMAN catalog in 9i

    Hi, I can't find this information in any documentation, so this is the best place for it. Can we create a 10g RMAN catalog on 9i database? If no why? If yes, then is there any known issue/problem with this? Thanks....

  • Controlling the root timeline from inside a MovieClip

    [preface] I'll apologize in advance. I'm a designer, not a developer. I know very little about actionscript so if you can help me out, please pretend like I know nothing. [/ preface] I just need actionscript to check the value of a variable when the