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

Similar Messages

  • Dynamic class loading from directory on server

    Hello,
    I am not sure if this is right forum, but I think it is more weblogic then ADF issue...
    I am trying to create and load dynamically classes in weblogic (10.3.2.0). It is ADF application which I deploy to the weblogic server.
    When I print ((GenericClassLoader)this.getClass().getClassLoader()).getFinderClassPath()I see the path to my directory (of course not just this path) C:\...\system11.1.1.2.36.55.36\DefaultDomain\servers\DefaultServer\tmp\_WL_user\test\753the\dynamicClasses(I have added directory dynamicClasses to manifest for deployment WAR profile).
    In this directory I create class files. I have checked it, files are really created there.
    When I try to load created class with the same classloader, for which I have printed classpath, ClassNotFoundException is thrown.
    Please where could be the problem? Isn't it possible to load classes from directory instead of jar, do I need some special server configuration,...?
    Thank you in advance
    Qjeta

    Hi Qjeta,
    I am not sure but you can give it a try using URLClassLoader...Which we generally use for DynamicClassLoading:
    import java.net.URLClassLoader;
    <font color=maroon>
    String path="C:/.../system11.1.1.2.36.55.36/DefaultDomain/servers/DefaultServer/tmp/_WL_user/test/753the/dynamicClasses";
    *URLClassLoader loader = new URLClassLoader(new URL[] { new URL(path) });*
    Class c = loader.loadClass ("your.class.NameHere");
    </font>
    // Load class from class loader. filly qualified class name (means classname with package name) is the name of the class to be loaded
    in the above code the "C:/.../system11.1.1.2.36.55.36/DefaultDomain/servers/DefaultServer/tmp/_WL_user/test/753the/dynamicClasses" should be the location of the directory where your classes are placed....If you want to load a perticular Jar then you need to write the jarfile name as well like following:
    C:/.../system11.1.1.2.36.55.36/DefaultDomain/servers/DefaultServer/tmp/_WL_user/test/753the/dynamicClasses/Myapplication.jar
    .================================
    If the above code works for you then later you can even try to enhance your code by doing the following:
    Thread.currentThread().setContextClassLoader(urlClassLoaderRef);
    Thanks
    Jay SenSharma
    http://jaysensharma.wordpress.com (WebLogic Wonders Are Here)

  • Dynamic class loading from JARs in web application

    Hello,
    I'm working on a web project in which we would like to dynamically load plugins without server restart.
    We have developed our own ClassLoader in order to load the plugins from a path or with a user interface upload function.
    The class loader hierarchy should be something like this:
          Bootstrap
              |
           System
              |
           Common
    Catalina   Shared
            Webapp1  OurSystem
                       PluginClassLoaderThe all works fine within the classes loaded in the PluginClassLoader, but classes loaded in OurSystems class loader cannot access classes loaded in PluginClassLoader. For example when Hibernate tries to load classes definied in mapping files we got a java.lang.ClassNotFoundException.
    Is there a way to load classes dynamically to OurSystems class loader or notify it about PluginClassLoaders classes?
    Or is this a bad way to do it?
    Best regards,
    Kristoffer Renholm

    Hi,
    Sounds like a classpath problem that the folks in the workshop newsgroup
    could help with. Try asking your question in:
    http://newsgroups.bea.com/cgi-bin/dnewsweb?cmd=xover&group=weblogic.developer.interest.workshop&utag=
    Bruce
    Graeme Dougal wrote:
    >
    Hi, I am developing a web service with weblogic workshop. The JWS file references
    other classes one of which is a factory for distributing various implementations
    of an interface. I am trying to dynamically load the relevant class to be distributed
    from the factory via its name, e.g. Class c = Class.forName(className)
    However I keep getting a classNotFoundException.
    Any ideas ??

  • 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();

  • 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 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 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 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 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();

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

  • 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

  • Error building project using kXML2 - "Class loading error: Wrong name"

    Hi,
    I'm testing the XML-Parser KXML2 and downloaded the latest package, but the minimal version (kxml2-min.zip). I put this file into the directory "%j2mewtk%\apps\KxmlTest\lib" and wrote the lines
    import org.kxml2.io.*;
    import org.xmlpull.v1.*;
    When I try to build the project with the Wireless Toolkit (v1.04) it spits out the following error:
    Error preverifying class kxml2.io.KXmlParser
    Class loading error: Wrong name
    com.sun.kvem.ktools.ExecutionException: Preverifier returned 1
    Build failed
    I also tried the full package "kxml2.zip" but the same error occurs.
    How can I get rid of this? Thanks in advance!

    Okay, finally worked it out (hopefully). I unpacked the archive to a directory (say "%J2MEWTK%\apps\KxmlTest\tmpclasses") and then preverified them "manually":
    %J2SDK%\bin\preverify.exe -classpath "%J2MEWTK%\apps\KxmlTest\tmpclasses";"%J2MEWTK%\lib\midpapi.zip" org.kxml2.io.KXmlParser
    %J2SDK%\bin\preverify.exe -classpath "%J2MEWTK%\apps\KxmlTest\tmpclasses";"%J2MEWTK%\lib\midpapi.zip" org.xmlpull.v1.XmlPullParser
    %J2SDK%\bin\preverify.exe -classpath "%J2MEWTK%\apps\KxmlTest\tmpclasses";"%J2MEWTK%\lib\midpapi.zip" org.xmlpull.v1.XmlPullParserException
    Then I packed them again to a jar-file:
    %J2SDK%\bin\jar.exe -cvf kxml2-min.jar %J2MEWTK%\apps\KxmlTest\tmpclasses\output\.
    That was all!

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

Maybe you are looking for