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

Similar Messages

  • 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 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 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).

  • 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

  • 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 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..

  • 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.

  • 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 in an EJB Container

    Hello,
    We have a need to load classes from a nonstandard place with in an ejb container, ie a database or secure store. In order to do so we have created a custom class loader. Two issues have come up we have not been able to solve, and perhaps some one knows the answer to.
    Issue 1.
    Given the following code:
    public static void main(String args[])
    MyClassLoader loader = new MyClassLoader("lic.dat");
    System.out.println("Loading class ..." + "TestObject");
    Object o = Class.forName("TestObject",true,loader).newInstance();
    System.out.println("Object:" + o.toString());
    TestObject tstObj = (TestObject) o;
    tstObj.doIt();
    What happens when executed is as follows. Class.forName calls our loader and does load the class as we hoped, it returns it as well, and the o.toString() properly executes just fine. The cast of the object to the actual TestObject fails with a class not found exception. We know why this happens but don't know what to do about it. It happens because the class that contains main was loaded by the system class loader (the primordial class loader as its sometimes called), That class loader does not know about TestObject, so when we cast even though the class is "loaded" in memory the class we are in has no knowledge of it, and uses its class loader to attempt to find it, which fails.
    > So the question is how do you let the main class know to use our class loader instead of
    the system class loader dispite the fact is was loaded by the system class loader.
    Issue 2:
    To make matters worse we want to do this with in an EJB container. So it now begs the question how do you inform an EJB container to use a specific class loader for some classes?
    Mike...

    Holy crap! We are in a similar situation. In creating a plugin engine that dynamically loads classes we use a new class loader for each plugin. The purpose is so that we can easily unload and/or reload a class at runtime. This is a feature supposedly done by J2EE app servers for hot-deploy.
    So our plugins are packaged as JAR files. If you put any class in the CLASSPATH, the JVM class loader (or the class loader of the class that is loading the plugin(s)), will load the class. The JavaDoc API states that the parent classloader is first used to see if it can find the class. Even if you create a new URLClassLoader with NULL for parent, it will always use the JVM class loader as its parent. So, ideally, in our couse, plugins will be at web sites, network drives, or outside of the classpath of the application and JVM.
    This feature has two benefits. First, at runtime, new updates of plugins can be loaded without having to restart the app. We are even handling versions and dependencies. Second, during development, especially of large apps that have a long startup time, being able to reload only one plugin as opposed to the annoying startup time of Java apps is great! Speeds up development greatly.
    So, our problem sounds just like yours. Apparently, the Client, which creates an instance of the plugin engine, tries to access a plugin (after the engine loades it via a new classloader instance for each plugin). Apparently, it says NoDefClassFound, because as you say, the client classloader has no idea about the plugin class loaded by another classloader.
    My co-developer came up with one solution, which I really dont like, but seems to be the only way. The client MUST have the class (java .class file) in its classpath in order to work with the class loaded by another class loader. Much like how in an EJB container, the web server calling to EJB MUST contain the Home and Remote interface .class files in its classpath, the same thing needs to be done here. For us, this means if a plugin depends on 5 others, it must contain ALL of the .class files of those plugins it depends on, so that the classloader instance that loads the plugin, can also see those classes and work with them.
    Have you got any other ideas? I really dislike that this has to be done in this manner. It seems to me that the JVM should be able to allow various class loaders to work with one another in such a way that if a client loaded by one classloader has an import statement in it to use a class, the JVM should be able to fetch the .class out of the other classloader and share it, or something!
    This seems to me that there really is no way to actually properly unload and then reload a class so that the JVM will discard and free up the previous class completely, while using the new class.
    I would be interested in discussing this topic further. Maybe some others will join in and help out on this topic. I am surprised there isn't a top-level forum topic about things like class loaders, JVM, etc. I wish there was a way to add one!

  • 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.

  • Dynamic class loading over a network

    hi,
    Im tryin to run a simple little "Hello World" type app using RMI. What i want to know is what permissions i need to grant inorder to dynamically load (client side) the stubs and skeletons from my server. Currently i get an UnmarshalException with a nested ClassNotFoundException and the helpful message "access denied to class loader". Any help is appreciated.
    Thanks in advance,
    Alex

    It is hard to tell what the problem is with out a stack trace from the exception. Perhaps in the future you would be kind enough to supply one.

Maybe you are looking for

  • Resizing Motion Jpeg video without applying any transcoding

    Hello, My apology if this is a silly question. I have Motion Jpeg video clip, which I need only to resize from 1920x1080 to 768x432. I want to leave codec, output fields and everything else as it is. What would be the best way to do this? Thank you s

  • BEFW11S4 v2 Wireless Problems w/ Vista

    I've have a BEFW11S4 v2 (firmware version: 1.45.10) wireless router for several years.  For the past year I've been running a Vista laptop along with my XP desktop.  The Vista laptop has been connected via wireless and desktop wired for the past year

  • Connecting a song ps3 to an hp touchsmart 310

    Is this even at all possible? I was told by the people who sold it to me, but Looking at it, I'm not too sure

  • Create frozen alv grid using salv* classes

    Hi Experts, I want to create a frozen alv grid i.e the row selections are defined in the code and should not be able to modify on the screen . Please let me know if it is possible ? I am using salv* class for alv. Thanks, Kiran A.

  • Styling of controls does'nt work  programmatically

    Hallo,      I have a stylesheet (mystylesheet.css) with following entry: .flowpane{     -fx-background-color: rgb(0,0,0); in then start-method of my application I execute:         StackPane root = new FlowPane();         Scene scene = new Scene(root,