Dynamic package loading..

Hello all,
Here is what I am trying to do. We have a jar package which is dynamic in nature. To avoid bringing down the server every time it gets changed, we decided to bring in the dynamic mode of loading packages. We decided to use the URLClassLoader against a jar package posted on a remote server.
But I am stuck at a point. Despite the change in the remote package and getting reloaded, the class being executed remains the old one. Here is a sample of what I am trying to do :
import java.net.*;
import java.io.*;
public class TestURLClassLoad {
     public static void main(String[] args) {
          try {
               String urlString = "jar:http://myhost/test.jar!/";
               URL[] urls = new URL[1];
               urls[0] = new URL(urlString);
               URLClassLoader ucl = new URLClassLoader(urls);
               Class myClass = ucl.loadClass("MyClass");
               Object myObject = myClass.newInstance();
               ucl = null;
               myClass = null;
               myObject = null;
               try {
                    Thread.sleep(10000);
                    // I have modified the Jar package at this point ..
               }catch(Exception e1) {}
               ucl = new URLClassLoader(urls);
               myClass = ucl.loadClass("MyClass");
               myObject = myClass.newInstance();
          catch(Exception e) {
               e.printStackTrace();
}The new instance however generates the same, old class. The new class is not being loaded in.
Any inputs on how to make this work ?
Thanks so much.

I realize this post is from a long time ago but someone may be able to help explain why when you create a newInstance() of a class and you check it it is an instanceOf an interface it always returns false. Here is a modified main() of the sample given:
public static void main(String[] args) throws Exception {
      File file = new File("myJAR.jar");
      JARClassLoader2 loader = new JARClassLoader2(file);
      Class[] classes = loader.getClasses();
      for (int i = 1; i < classes.length; i++) {
         System.out.println("Class: " + classes.getName());
Object o = classes[i].newInstance();
if (o instanceof SomeInterface) {
System.out.println("Instance of TextProcessingRoutine = true");
I have noticed this ONLY returns false if the classes are in a package.  If they are in no package (or default package for eclipse) it works fine.
And I know 100% that the classes I am checking are an instance of SomeInterface.
Thanks,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Dynamic Package Loading/Importing

    Hi,
    I'm developing an open framework for network admission control / network access protection which bases on independent modules handling different procedures like authentification, accounting and so on.
    Right now I dynamically load my modules into my framework at startup or during runtime (hot-pluggable) using the well-known simple method:
    className = "package.classname" // just an example
    rawClass = Class.forName(className);
    newModule = (AModule) rawClass.newInstance();
    This works fine as long as
    - The module which is going to be loaded only consists of one class and doesn't need other classes (e.g. for Dispatcher Threads ...) to run. This would still be no problem if I simply place all needed classes in the right directories, but I'd like to ship modules as packages for an easier handling of new modules.
    - The module doesn't need any libraries like e.g. the mySQL-JDBC-Connector. Right at this point I run into serious troubles cause I've to specify these external jars before starting my framework (java -cp ...).
    I haven't found any way to dynamically extend the classpath / to add whole jar's/packages during runtime yet so hopefully anyone could give me a hint how to implement that.
    In short I'd like to implement the following functionality: Without being in classpath at startup a package should be accessible and all classes of the package should be loadable - more or less like being in classpath but without being specified to be in classpath at startup.
    Thank you very much in advance
    Bastian

    Hi,
    Like different classes that you created? Then you
    put them in the same jar.
    Even if you put them in seperate jars the original
    jar has to get into the class path somehow. And
    those other jars would get there the same way.For sure the framework itself is in one single JAR included in the classpath (or if extracted the class files lie in a path hierarchy included in the classpath).
    Again the first class MUST be in your class path for
    the code that you posted to work. I know that it has to be - but I'd like to avoid that. The code I've posted is the way it works right now. But I'd like to change that so that I don't need the first class to be in the class path.
    That requires that you do something to get them
    there.That's what I'm trying to find out - how can I get classes into the classpath after having started the runtime if they are bundled in external JARs (like e.g. the JDBC)?
    How exactly are you currently delivering your stuff?I don't deliver any modules yet because I'd like to find a proper and easy way to handle that class/package loading problem before putting the project online.
    My idea is:
    - One JAR for the framework including all classes without modules.
    - One JAR for every module which should be loaded and instantiated at runtime as defined in a global configuration file with the capability of "hot plugging", which means that I'm able load/start and stop/unload modules during runtime whenever I'd like to.
    To implement the second part I guess I need a way to dynamically extend the classpath or dynamically load JARs.
    There is no way to extend the class path. That is a
    security feature of java.I see. What about the JarLoader I've found in the meanwhile written by Melanie Green. Is it a proper workaround?
    You might note also that for the previous suggestion
    it is complicated to load a jdbc driver via a
    classloader. You can not use the standard code to do
    it. There is a thread in the JDBC forum about this.I'll take a look - thank you very much!
    Bastian

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

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

  • SSIS Package Load Failure and is missing Execute SQL Task in Toolbox

    Also, BIDS closes after right-clicking the toolbox and selecting “Choose Items”.
    I’ve tried several ways to fix these issues with no success.
    I’m running SSIS/SSMS/SQL Server 2008 R2 (but not running an SQL instance on my PC) on a Windows XP with Service Pack 3 workstation. I get the following errors:
    WHEN OPENING BIDS:
    I get 2 errors titled “Package Load Failure”. They both reference ‘Visual Studio Explorers and Designers Package’ as being what failed to load. The first message references GUID 8D8529D3-625D-4496-8354-3DAD630ECC1B. The second references GUID AA612177-A69A-4391-B2F4-17F8A88F4BBA
    . They both mention contacting the package vendor, but I haven’t got any Add-ins loaded so I’m not sure what that means exactly. They also both ask if I’d like to skip loading the package in the future.
    ONCE BIDS IS OPEN:
    No error messages appear here. There is no ‘Execute SQL Task’ in the toolbox for Control Flows. Also, if I attempt to open a project containing this object (Execute SQL Task), I get this error in a modal window:
    TITLE: Microsoft Visual Studio
    There were errors while the package was being loaded.
    The package might be corrupted.
    See the Error List for details.
    BUTTONS:
    OK
    . . . and these errors in the Error List at the bottom of the IDE:
    Error      1             
    Error loading Package.dtsx: Failed to load task "Execute SQL Task", type "Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask.ExecuteSQLTask, Microsoft.SqlServer.SQLTask, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91". The contact information
    for this task is "Execute SQL Task; Microsoft Corporation; Microsoft SQL Server 2008 R2; © 2007 Microsoft Corporation; All Rights Reserved;http://www.microsoft.com/sql/support/default.asp;1". 
            C:\Documents and Settings\848862.VCHS_NT_DOMAIN\My Documents\Visual Studio 2008\Projects\LearnSSIS\LearnSSIS\Package.dtsx   
    1               
    1             
    Error      2             
    Validation error. Execute SQL Task : The task has failed to load. The contact information for this task is "Execute SQL Task; Microsoft Corporation; Microsoft SQL Server 2008 R2; © 2007 Microsoft Corporation; All Rights Reserved;http://www.microsoft.com/sql/support/default.asp;1". 
            Package.dtsx    
    0             
    0             
    Error      3             
    Validation error. Execute SQL Task : There were errors during task validation. 
       Package.dtsx    
    0             
    0               
    Finally, when I attempt to add the Execute SQL Task via the Tools menu, “Choose Toolbox Items” selection, I do get the tabbed box for adding things. However, they only come up after issuing this error:
    The following assemblies are installed SDK assemblies but could not be shown in the customize toolbox dialog because they are missing one or more components. Please make sure that all necessary libraries are available:
    Microsoft.SqlServer.SqlCEDest.dll
    Microsoft.SqlServer.Management.CollectorTasks.dll
    Microsoft.SqlServer.SQLTask.dll
    System.Data.SqlServerCe.dll
    Microsoft.Synchronization.Data.SqlServerCe.dll
    (above dll repeated at bottom of message)
    After this message, I have my choice of .NET Framework Compnents. When I select COM Components, those come up with no problem. The WPF Components tab generates the same dll error above. The Maintenance tab is empty. The SSIS Data Flow Items tab loads fine,
    as does the SSIS Control Flow Items tab – but there’s no Execute SQL Task there either.
    If you open the toolbox (on a new project, with a project loaded, or without a project loaded) and right-click, then select “Choose Items”, the entire application quickly closes. This “closing behavior” is the same thing you get if you attempt to add toolbox
    items through either the Tools menu or the right-click method when you launch BIDS in SafeMode.
    In an effort to fix this – I’ve rolled back the .NET Framework version to 3.0 and reinstalled back up to 4; I’ve uninstalled and reinstalled SQL Server 2008 R2 shared services as well as the entire application; I’ve cleared the .tbd files from my user profile;
    and I’ve run several things from the command line (devenv.exe /resetuserdata, /setup, /resetskippkgs, etc.). Lastly – I’ve applied every Service Pack and update applicable to my PC (ok, it belongs to my employer – but no one here has been able to figure this
    out either).
    After having worked this for several days now and, I think, exhausting every available avenue from search engines – I turn to you. Please let me know if you can help. Also, I can provide any additional
    files or information you may require.
    CBS

    try: Devenv.exe /ResetSettings
    http://msdn.microsoft.com/en-us/library/ms241273(v=vs.80).aspx
    Or try this (it's for 2005, but maybe it works for 2008 aswell):
    http://geekswithblogs.net/cicorias/archive/2007/10/10/Restoring-Missing-Toolbox-Items-in-Visual-Studio-2005---just.aspx
    or try
    http://stackoverflow.com/questions/1268298/how-to-rebuild-the-visual-studio-toolbox
    "You can also go into the folder "C:\Documents and Settings\\Local Settings\Application Data\Microsoft\VisualStudio\9.0" and delete the *.tbd files.  I have had to do this a couple times to get rid of duplicate items and when Reset Toolbox crashes
    without warning"
    Please mark the post as answered if it answers your question | My SSIS Blog:
    http://microsoft-ssis.blogspot.com |
    Twitter

  • Package load Failed! Invalid package Title, manifest file cannot be found

    Greetings. I am new to UPK and am seeking guidance on an upgrade to 11.1.
    A little background on what we are trying to do:
    We have two machines:
    Windows 2003 machine in domain 'X' | UPK 11.0.0.1.
    Windows 2008 R2 virtual machine in domain 'Y' | UPK 11.0 on the new machine first, install the 11.0.0.1 patch, and then upgrade to 11.1.
    We are using the same database as the old machine. Developer Server is Standard Authentication, Knowledge Center is Windows authentication.
    ==========================================================================================
    So far we have installed 11.1 with the respective database upgrades, but are lost as to how to migrate the old Content Root data. We have copied all the content to the new Content Root, added it to IIS like the old machine, and verified that the UPK database Content Root path is correct and working.
    For the rest of the post, I am remoted into the server from my local workstation, and then using IE to access KCenter on the server's FQDN, not via localhost.
    Since I am green, so I presumed that I would need to import the titles under Manager in KCenter. I zipped each content folder individually (they are named "1", "9", etc), and then attempted to import each zip file.
    NOTE: At this stage sometimes we are prompted to authenticate again. When it does, sometimes the credentials that we know work, get rejected and we are prompted again. This will repeat until we get a 401 and we have to start over. We have verified that the Windows account currently in session with the site is valid and has administrator authority within KC.
    NOTE2: On the first few tries, .NET complained that maxRequestLength was not large enough. I had our servers team increase it on the actual server in order for us to proceed.
    Provided we don't have to authenticate again, or that it actually accepts our credentials, we get to the 30% mark and then receive the error: *"Package load Failed! Invalid package Title, manifest file cannot be found"*
    Does anyone have any wisdom for this process? The title importation section in the deployment manual is not helping, and the administrator from whom I am taking over this software has not had to deal with this before.
    Thank you,
    Ian
    Edited by: 986290 on Feb 5, 2013 10:21 AM

    Hi Marc, thanks for the post,
    I have gone through an extensive troubleshooting process with Oracle, including their development team, in order to fully complete our project setup. As a supplemental bit of information, we also were having connection errors when attempting to publish directly to the knowledge center.
    As far as the context of this post, here is the solution in brief:
    1) Verify that the package being imported was published from the same version of the Developer Client as the Knowledge Center installation's.
    2) Check for database consistency issues. In our case we were using a database that was built in another domain. After numerous attempts with Oracle support on the line to determine the inconsistency, it was decided to completely reinstall and build a new database from scratch in the new domain.
    3) Check application pool identities and access (while we had some inconsistencies here, correcting them did not change the behavior of the import/publish errors)
    In review, a lot of what we had setup was correct. Our primary point of failure, we feel, was using the old database. Technically this should not have been a problem, but Murphy likes to get his way sometimes.
    Cheers,
    Ian

  • Package loading error

    Hi guys and girls
    I have develoed sim toolkit applet to send sms,its complied sucessfully and also converted successfully.But when i am loding this applet to
    java card its giving error like this:
    [b]error:package loading failed !
    loading ended with error:loading process failed1 !
    i am using simera 3 classic323 vodafone javacard.
    any suggestions will be highly appriciated.

    Hi,
    The selection condition is only planning version 700. There is no other selection conditions.
    I checked the process monitor and I can only find error messages Time Period Invalid and Errors in Source system. This error messages are not enough for trouble shooting.
    thanks and regards
    Murugesan

  • Package Load Failure message in VS 2005 and Error: WIJ 20002

    After installing BusinessObjects Enterprise XI 3.1 .NET SDK when ever I open any project in VS 2005 I get the error message (the same happened on other system as well)
    Package Load Failure
    Package 'BusinessObjects.Enterprise.Vsip.BOEVsPackage, BOEVsPackage, Version=12.0.2000.0, Culture=neutral, PublicKeyToken=... has failed to load properly (GUID = {...}). Please contact package vendor for assistance. Application restart is recommended, due to possible environment corruption. Would you like to disable loading this package in the future? You may use 'devenv /resetskippkgs' to re-enable package loading.
    I did try 'devenv /resetskippkgs' but still get this error. Any idea reagarding this.
    Next issue using the code sample provided in the site to create webi document by passing the universe id gives error message :
    "The Web Intelligence Java Report Panel cannot connect to the server. close the report panel and try to connect again or see your BO Administrator. (Error: WIJ 20002)."
    The Java version I have is 6 and I checked the Universe is not locked.
    Need help to identify the cause for both errors.

    Try the following as posted on another forum:
    Two solutions: 
    1.  -Go in to the Tools menu in .NET, and choose Import and Export Settings.
        - From the dialogue box, choose Reset All Settings and follow the steps
    2. If you have installed VS.NET to a drive other than the C drive, copy all files from the folder C:\Program Files\Microsoft Visual Studio 8\Common7\IDE to the same folder on the drive where .NET is installed, ie :
    D:\Program Files\Microsoft Visual Studio 8\Common7\IDE
    Regards,
    Jonathan

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

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

Maybe you are looking for

  • How to make new line in JButton.setText()?

    how to make new line in JButton.setText()? I want to set the text of jbutton in tow line ,as follows | jbutton-line1 | | xxxxxxx-line2 | i konw i can jbtton.settext("<html>line1<br>line2</html>"); but i find it's ugly using html, is there anyother wa

  • Problem with NOKIA 5800 Music Express

    Hi all, My NOKIA 5800 hasnt been working properly for some time. I can not make a call using my phone book (only if i dial the number i can call) though incoming call can be received. Apart from that, when i try to navigate tomy memory card, i cant a

  • Kernel Panic in MacBook Pro

    Hi, Recently, we're having lots of problem with one of our MacBook Pro. It always goes to Kernel Panic. Here's the log. Thank you. Any help will be very much appreciated. Wed Jan 24 10:36:17 2007 panic(cpu 0 caller 0x001A3135): Unresolved kernel trap

  • IOS7 Notifications not showing in the lock screen

    Hello, During the day, my notifications in the lock screen show up without a problem. The problem is that for long periods of time, notifications do not show up in the lock screen. When I wake up in the morning to check the lockscreen, notifications

  • Best methods for large To: list using cfmail

    I'm getting time-out errors on one of my sites. People can post to a message "corkboard" and site members can subscribe. One of the topics has close to 600 subscribers. The SMTP mail server is IIS's built-in thing, on the same machine as the web serv