Problem with dynamic class loading

Hi,
We have a class file in an external jar(outside ear) and access it in an ear using classloader.loadClass method. But if the class file is changed in jar, it gets hotdeployed in jboss but code which calls this class still refers to the old code.
Class getClassByName(String className) throws ClassNotFoundException {
Class theClass = null;
try {
theClass = Thread.currentThread().getContextClassLoader().loadClass(className);
} catch (ClassNotFoundException e) {
theClass = getClass().getClassLoader().loadClass(className);
return theClass;
When I looked into api I came to know that loadClass actually loads the class if it is not already exists. Can any one help me in writing thecustom class loader which loads the class everytime instead of checking previous instance before loading......
Thanks,
Kruthika

You probably have to get rid of the class loader that loads the original version and start with a new class loader.

Similar Messages

  • Problem with Dynamically accessing EJB Class objects in WL 7.0 SP1

    I am trying to build a component which has the ability to instantiate and execute
    an known EJB method on the fly.
    I have managed to build the component but when I try and execute it I get a ClassNotFoundException.
    I know that the EJB I am trying to invoke is deployed and available on the server,
    as I can see it in the console, I also seen to have been able to get the remote
    interface of the object, my problem occurs when I try and access the class object
    so I can perform a create on the object and then execute my method
    The code I have written is below:
    private Object getRemoteObject(Context pCtx, String pJNDIName, String pHomeBean)
    throws Exception {
         String homeCreate = "create";
         Class []homeCreateParam = { };
         Object []homeCreateParamValues = {};           
    try {  
    //This call seems to work and doesn't throw an exception     
    Object home = pCtx.lookup(pJNDIName);
    //However this call throws a java.lang.ClassNotFoundException
    Class homeBean = Class.forName(pHomeBean);
    Method homeCreateMethod = homeBean.getMethod(homeCreate,homeCreateParam);
    return homeCreateMethod.invoke(home, homeCreateParamValues);
    } catch (NamingException ne) {             
    logStandardErrorMessage("The client was unable to lookup the EJBHome.
    Please make sure ");
    logStandardErrorMessage("that you have deployed the ejb with the JNDI
    name "+pJNDIName+" on the WebLogic server ");
    throw ne;
    } catch (Exception e) {
    logStandardErrorMessage(e.toString());
    throw e;     
    Any advice would be really appreciated, I'm fast running out of ideas, I suspect
    it has something to do with the class loader but I'm not sure how to resolve it
    Regards
    Jo Corless

    Hello Joanne,
    Congratulations! I'm very happy that you've managed to fix your problem. It's
    always essential to understand how to package applications when deploying on BEA
    WebLogic. Usually, by throwing everything into an EAR file solves just about all
    the class loader problems. :-) Let us know if you have any further problems that
    we can assist you with.
    Best regards,
    Ryan LeCompte
    [email protected]
    http://www.louisiana.edu/~rml7669
    "Joanne Corless" <[email protected]> wrote:
    >
    >
    I've fixed it!!!!!!!!
    Thanks to everyone who gave me help!!!!
    The class loader was the culprit which is what I suspected all along.
    As soon
    as I put the 2 jar files I was using into an EAR file the problem went
    away!!!!!
    Thanks again
    Jo Corless
    "Ryan LeCompte" <[email protected]> wrote:
    Hello Joanne,
    As Mr. Woollen mentioned, I also believe it's a problem with the class
    loader.
    You need to be careful how you arrange your EJBs, because WebLogic has
    a specific
    method in which it loads classes in an EAR, JAR, and WAR file(s). Please
    refer
    to http://dev2dev.bea.com/articles/musser.jsp for more information about
    BEA WebLogic
    class loading mechanisms and caveats. Also, try printing out the various
    methods
    that are available on the object that was returned to you via reflection.
    For
    example, use the getMethods() method, which returns an array of Method
    objects
    that you can subsequently cycle through and print out the various method
    names.
    This way you can discover if the class found/returned to you is indeed
    the one
    you intend to locate.
    Hope this helps,
    Ryan LeCompte
    [email protected]
    http://www.louisiana.edu/~rml7669
    Rob Woollen <[email protected]> wrote:
    I believe the issue is the home interface class for this EJB is not
    available in the class loader which is doing the reflection.
    If you do:
    getClass().getClassLoader().loadClass(homeInterfaceClassName)
    I suspect it will fail. Reflection still requires that the class be
    loadable.
    -- Rob
    Joanne Corless wrote:
    Hi Slava,
    If I make my code look like you describe below I get a compliationerror telling
    me that
    home.getMethod() is not recognised (no such method)
    If I change it slightly and use
    Method homeCreateMethod =
    home.getClass().getMethod(homeCreate,homeCreateParam);
    The code will compile OK but when executed it still throws a NoSuchMethodException
    Any ideas ?
    Thanks for your help so far
    Regards
    Jo Corless
    Your code should look like
    Object home = pCtx.lookup(pJNDIName);
    Method homeCreateMethod =
    home.getMethod(homeCreate,homeCreateParam);
    return homeCreateMethod.invoke(home, homeCreateParamValues);
    Regards,
    Slava Imeshev
    "Joanne Corless" <[email protected]> wrote in message
    news:[email protected]...
    Hi Ryan,
    I also wanted to mention that if you do a "header search" in this
    particular
    newsgroup
    with the search query as "reflection", you will see many previousmessages
    regarding
    reflection and EJBs. I believe you could learn a lot from thedifficulties
    that
    others have faced and solved.I tried that and although there was a number of similar cases noneof them
    actually
    seem to fix my issue. Thanks for the suggestion though
    Are the EJBs that you are trying to access accessible via your
    system
    classpath?
    Try to avoid having them accessible via the main system classpath,and
    only bundle
    them in your appropriate EJB jar files (contained in an EAR file,for
    example).Maybe I should have laid the problem out a little clearer.
    I have a number of EJB's bundled up in a JAR file which is hot deployedto
    the
    server. Within this first JAR file is an EJB (SSB) component that
    needs
    to
    be
    able to invoke a known method on another EJB. This second EJB may
    or
    may
    not be
    within the first JAR file but it also will be hot deployed.
    The component trying to invoke the method on the 2nd EJB has to
    be
    able to
    create
    an instance of the 2nd EJB without actually knowing anything bar
    a
    JNDI
    Name which
    is passed in at runtime.
    I can get as far as doing the
    Object home = pCtx.lookup(pJNDIName);
    This returned a class with the name
    "com.csc.edc.projects.allders.httppostoffice.postman.PostmanBean_mp8qy2_Home
    Impl_WLStub"
    My problem seems to occur when I try and invoke the create method
    Method homeCreate = home.getClass().getMethod("create", new Class[0]);
    My code throws a java.lang.NoSuchMethodException at this point so
    I
    am
    unable
    to progress to the next step of :
    Object bean = homeCreate.invoke(home, null);
    So I can return the instantiated bean back to the calling client.
    Why am I getting the NoSuchMethodException, is is because I am gettinga
    stub
    back rather than the home interface and if so how do I get the truehome
    interface
    from the bean
    Thanks in advance
    Jo Corless

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

  • Problem with module lazy loading in flex 3

    Hi every body!
    I have some problems with Module lazy loading. I am using flex 3.5, Module-flex3-0.14, parsley 3.2.
    I can't get the LazyModuleLoadPolicy working correctly.
    In my main application (the one that loads the modules), my parsley context is the following:
            <cairngorm:LazyModuleLoadPolicy objectId="lazyLoadPolicy" type="{ OpenViewMessage }" />
         <cairngorm:ModuleMessageInterceptor type="{ OpenViewMessage }"/>
         <cairngorm:ParsleyModuleDescriptor objectId="test"
              url="TestModule.swf"
              applicationDomain="{ClassInfo.currentDomain}"
         />
    And to load my module:
    [Inject(id="test")]
    [Bindable] public var test:IModuleManager;
    <core:LazyModulePod
         id="moduleLoader"
         moduleManager="{test}"
         moduleId="testModule"
    />
    with  LazyModulePod.mxml:
    <mx:Canvas
        xmlns:mx="http://www.adobe.com/2006/mxml"
        xmlns:module="com.adobe.cairngorm.module.*"
        xmlns:parsley="http://www.spicefactory.org/parsley">
        <mx:Script>
            <![CDATA[
                import com.adobe.cairngorm.module.ILoadPolicy;
                import com.adobe.cairngorm.module.IModuleManager;
                [Bindable]
                public var moduleId:String;
                [Bindable]
                public var moduleManager:IModuleManager;
                [Bindable]
                [Inject(id="lazyLoadPolicy")]
                public var lazyLoadPolicy:ILoadPolicy;
            ]]>
        </mx:Script>
        <parsley:Configure/>
        <module:ViewLoader id="moduleLoader"
            moduleId="{ moduleId }"
            moduleManager="{ moduleManager }"
            loadPolicy="{lazyLoadPolicy}">
             <!--<module:loadPolicy>
                  <module:BasicLoadPolicy/>
             </module:loadPolicy>-->
        </module:ViewLoader>
    </mx:Canvas>
    OpenViewMessage.as in a swc:
    public class OpenViewMessage
            private var _moduleId:String;
            private var _viewId:String;
            public function OpenViewMessage(moduleId:String, viewId:String)
                this._moduleId = moduleId;
                this._viewId = viewId;
            public function get viewId():String{
                return _viewId;
            [ModuleId]
            public function get moduleId():String
                return _moduleId;
    In another flex project, my module context is:
    <mx:Object
         xmlns:mx="http://www.adobe.com/2006/mxml"
         xmlns:controler="com.cegedim.myit.controler.*">
         <controler:WindowControler/>
    </mx:Object>
    The module implements IParsleyModule
    <mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
         implements="com.adobe.cairngorm.module.IParsleyModule"
         xmlns:spicefactory="http://www.spicefactory.org/parsley">
         <mx:Script>
              <![CDATA[
                   import org.spicefactory.parsley.flex.FlexContextBuilder;
                   import com.adobe.cairngorm.module.IParsleyModule;
                   public function get contextBuilder():ContextBuilderTag
                    return contextBuilderTag;
              ]]>
         </mx:Script>
         <spicefactory:ContextBuilder  id="contextBuilderTag" config="{ MyITTestModuleContext }"/>
         <spicefactory:Configure/>
    </mx:Module>
    and the WindowControler:
    public class WindowControler
         public function WindowControler(){}
         [Init]
            public function initialize():void
                Alert.show("Module Initialized");
            [MessageHandler(scope="local")]
            public function openViewMessageHandler(message:OpenViewMessage):void
                Alert.show("Opening view " + message.viewId + " in the module " + message.moduleId);
    If i uncomment the basicLoadPolicy in LazyModulePod.mxml and remove the lazyModuleLoadPolicy, everything works fine. The module is loaded when it's added to stage and it receives correctly messages dispatched to it. But with the lazy policy the module never loads.
    I may have missed something or there is somthing i don't understand because i tried the ModuleTest provided in example in cairngorm sources. It works fine (i mean loading the moduleA2 when receiving a message), but if i replace the change the lazyModulePolicy to listen to broadcasted messages instead of a pingMessage, the module never loads too.
        <cairngorm:LazyModuleLoadPolicy objectId="lazyLoadPolicy" type="{ BroadcastMessage }" />
        <cairngorm:ModuleMessageInterceptor
            type="{ BroadcastMessage }" moduleRef="moduleA" />
    public class BroadcastMessage
        public function BroadcastMessage()
    If someone has any clue, i'll be happy to test it =)
    Thanks.

    Hello, back on my issue, i tested a little bit more the message dispaching.
    I read the lazyLoadPolicy class and noticed that it always has to have a ModuleId property in the message to work, that's why the broadcast message didn't work to awake the module with the lazy loading policy.
    So i added copy of my module:
         <cairngorm:ParsleyModuleDescriptor objectId="test"
              url="TestModule.swf"
              applicationDomain="{ClassInfo.currentDomain}"
         />
         <cairngorm:ParsleyModuleDescriptor objectId="testbis"
              url="TestModuleBis.swf"
              applicationDomain="{ClassInfo.currentDomain}"
         />     
    Set them both with a basicLoadPolicy, and tries to dispatch a message to only one of them using the ModuleId metatag. I then noticed that both modules received the message and not only the one i expected.
    I then changed the ModuleMessageInterceptor configuration to dispatch to only one kind of module:
    <cairngorm:ModuleMessageInterceptor type="{ OpenViewMessage }" moduleRef="test"/>
    and this worked as expected. Only the first module catched the message. I am obiously messing with the ModuleId metatag but i cannot see what's wrong...
    I compiled with
    -keep-as3-metadata+=ModuleId
    but this hasn't changed anything...

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

  • Problem with  whitespace  then loading and saving xml

    i do not know how to handle this problem. i modifed a texteditor to send XML to a server and load XML back to the container.
    but then i do changes to the Textlayout it shows up like this --->
    Text in Container not modifed
    Text in Container modifed ---> with space beween the colorchanged string
    Text inContainersend and loaded ---> i think this has something to to with the
    TextFilter.export(_textFlow,TextFilter.TEXT_LAYOUT_FORMAT,ConversionType.XML_TYPE)
    can someone give me a hint...

    Hi,
    the link is --->
    http://www.horstmann-architekten.de/contentmanagment/SimpleEditor.html
    its a modified example of the texteditor provided by Adobe. You can send a xml to the server. and also read it from the server. You just use the xml identifer to give the xml a name.
    Try it out:
    1.  change the text and
    2.  give a XML-Identifer
         and then send it to the server. --> send to server
    3.  type in the XML-Identifer you have used and
    4.   load it from the server ---> Load from Server Button
    evering works ok exept the columns formating.
    I Think the colums Formating is not embeded in the XML as it should be. I attached the Files. (Newbie programmer)
    With best regards
    Michael Sprinzl
    --- robin.briggs <[email protected]> schrieb am Do, 17.9.2009:
    Von: robin.briggs <[email protected]>
    Betreff: Problem with  whitespace  then loading and saving xml
    An: "Michael sprinzl" <[email protected]>
    Datum: Donnerstag, 17. September 2009, 2:12
    Sounds like you have two different issues going on: (1) inline graphics aren't coming out correctly when you use the TextLineFactory, and (2) columns aren't working correctly. It's difficult for me to tell by looking at the application you link what is going wrong. One of the examples does seem to have columns working -- can you be more specific about what you're doing, and what results you are seeing? As for the inline graphics, there is a timing issue involved with using URLs, due to the asynchronous loading. See this comment in the docs for TextFlowTextLineFactory:
    Note: When using inline graphics, the source property of the InlineGraphicElement object   must either be an instance of a DisplayObject or a Class object representing an embedded asset.   URLRequest objects cannot be used. The width and height of the inline graphic at the time the line   is created is used to compose the flow.
    - robin

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

Maybe you are looking for

  • Mini displayport to HTMI not working

    I recently bought a Belkin mini displayport to HTMI cable. I plugged everything up and both TVs in my house don't do anything. They say no signal. I turned them off, my MBP off and still nothing happens. Some research lead me to System Prefences-Disp

  • Week numbers in Month view

    Hi, How can i add week number in "month view"?  I can see week number in "week view" and i see that this can be fixed with a script. But the scrit under don't work for me!  =INT(([a2]-DATE(YEAR([a2]),1,1)+(TEXT(WEEKDAY(DATE(YEAR([a2]),1,1)),"d")))/7)

  • Development machine

    Hello OTN Members, I have a server box on win NT and Oracle 8.1.6, Portal 3.0 installed on it. I am planning to install Forms Developer 6i. My question is can I install form Developer 6i and forms Server on to this same box and for the development pu

  • Transporting Extract Structures for Business Content Data Sources

    Hi We have added a new field to the 2lis_13_vditm data source and when i am trying to capture it in the transport, only the data source is getting captured and not the extract sturcture. When I go to the Object Entry Directory of the Extract Structur

  • Returning unicode string through function argument.

    Hi all, I have following function written in a C++ dll. I need to be able to call it from Java using JNI. This function expects to receive a buffer pointed by wchar_t * of "int len" length. It will copy write some text in to this buffer and i need to