1 2 Previous Next 16 Replies Latest reply on May 6, 2007 7:23 PM by 800649

    running a java program using URLClassLoader

    807606
      I have been developing text editor for my final project which can compile and run java prorams.
      this is the code that i have written for running the class file that is created after compilation---

      import java.net.*;
      import java.net.URLClassLoader;
      import java.net.URL;
      import java.io.File;
      import java.lang.reflect.*;
      public class runMethod extends ClassLoader{
           public void run(String dir, String f){

                File file = new File(dir);
                File[] files = file.listFiles();
           URL[] urls = new URL[files.length];

                try{

                     URL url = file.toURL();
                }catch(MalformedURLException e) {
           System.out.println("MalformedURLException: " + e.getMessage());
           }
                     ClassLoader loader = new URLClassLoader(urls);
                try{
                          Class clazz = Class.forName(f, true,loader);
                          Method method = clazz.getDeclaredMethod("main", new Class[] { String[].class });

                          method.invoke(null, new Object[] {});
                     } catch (Exception ex) {
                     System.out.println(ex.getMessage());
                }

           }
      }

      But the output it gives me is not the running program but "null". please help me in figuring out what is the problem and why is it not running the class file and giving the output.
        • 1. Re: running a java program using URLClassLoader
          800649
          use
          e.printStackTrace();
          instead of
          System.out.println(ex.getMessage());
          This will display the exception message to help you debug your program.
          try{
          URL url = file.toURL();
          }catch(MalformedURLException e) {
          System.out.println("MalformedURLException: " + e.getMessage());
          }
          You never used the url you created !!


          Here another way to run your program:
          import java.lang.reflect.Method;
          
          public class RunMethod{
          
               public static void run(String dir, String f) {
                    try {
                         Class params[] = {String[].class};
                         Object paramsObj[] = {new String[]{}};
                         Class thisClass = Class.forName(f);
                         Object iClass = thisClass.newInstance();
                         Method thisMethod = thisClass.getDeclaredMethod("main", params);
                         thisMethod.invoke(iClass, paramsObj);
                    } catch (Exception e) {
                         e.printStackTrace();
                    }
               }
          
               public static void main(String[] args) {
                    run("PATH_TO_YOUR_PACKAGE", "yourPackage.yourClassName");
                          //exp : run("C:/DEV/java/MyProject/", "test.MyClass");
               }
          }
          • 2. Re: running a java program using URLClassLoader
            807606
            hey dude,
            first of all thanks for that. I tried to change my code a little bit and it goes like this::
            import java.net.*;
            import java.net.URLClassLoader;
            import java.net.URL;
            import java.io.File;
            import java.lang.reflect.*;
            public class runMethod extends ClassLoader{
                 public void run(String dir, String f){

                      File file = new File(dir);
                      File[] files = file.listFiles();
                 URL[] urls = new URL[files.length];
                      for(int i=0;i < files.length; i++){
                           try{

                                urls[i] = files.toURL();
                           }catch(MalformedURLException e) {
                      System.out.println("MalformedURLException: " + e.getMessage());
                      }
                      }
                           URLClassLoader loader = new URLClassLoader(urls);
                      try{
                                System.out.println("-----Output-----"+"\n");

                                Class clazz = Class.forName(f, true, loader);

                                //System.out.println(" this is????");

                                Method main= clazz.getDeclaredMethod("main", new Class[] { String[].class });

                                main.invoke(null, new Object[] {null});

                                
                           } catch (Exception ex) {
                           System.out.println(ex.getMessage());
                      }

                 }
            }

            but now the problem is that i get only the name of the class. but it does not invoke the main method. actually it does not go beyond
            Class clazz = Class.forName(f, true, loader);

            even the print statement after this line does not get printed!!!!!

            I also tried to implement your way but it also does not run the main method!!!
            when i try to put that code in to my run method!!!
            I will appreciate if you can help me out of it....

            I am not a big specialist in java but i dared to take up this project for my final project!!!
            • 3. Re: running a java program using URLClassLoader
              807606
              hey java_2006,
              after using the printStackTrace(), I found out that actually the it was an ClassNotFoundException.!!!!!

              can you tell me why that problem did arise????!!!
              • 4. Re: running a java program using URLClassLoader
                800649
                Please dont use System.out.println(ex.getMessage()); again, use e.printStackTrace(); !
                it was an ClassNotFoundException.
                ClassNotFoundException exception is thrown when an application tries to load in a class through its string name using:

                - The forName method in class Class.
                - The findSystemClass method in class ClassLoader .
                - The loadClass method in class ClassLoader.
                but no definition for the class with the specified name could be found.


                Post the last version of your program plz.

                By the way, the code I suggested works fine for me.
                • 5. Re: running a java program using URLClassLoader
                  800649
                  Here a complete example.

                  Suppose that your workspace is C:/java/projects/, that your project is called myproject and the build directory is called classes (myproject/classes/)

                  create the class MyTargetClass in a package called test1 :
                  package test1;
                  
                  public class MyTargetClass {
                       public static void main(String[] args) {
                            System.out.println("Hello from "+MyTargetClass.class.getName());
                       }
                  }
                  Create the class RunMethod in a package called test2 :
                  package test2;
                  
                  import java.net.*;
                  import java.io.File;
                  import java.lang.reflect.*;
                  
                  public class RunMethod {
                  
                       public void run(String dir, String f) {
                  
                            URL[] urls = null;
                  
                            try {
                                 // Convert the file object to a URL
                                 File myDir = new File(dir);
                                 URL url = myDir.toURL(); 
                                 urls = new URL[] { url };
                            } catch (MalformedURLException e) {
                                 e.printStackTrace();
                            }
                  
                            try {
                                 // Create a new class loader with the directory
                                 ClassLoader cl = new URLClassLoader(urls);
                  
                                 // Load in the class
                                 Class clazz = cl.loadClass(f);
                  
                                 // Create a new instance of the new class
                                 //MyTargetClass= (MyTargetClass) clazz.newInstance();
                  
                                 Method main = clazz.getDeclaredMethod("main", new Class[] { String[].class });
                                 
                                 main.invoke(null, new Object[] { null });
                  
                            } catch (Exception e) {
                                 e.printStackTrace();
                            }
                       }
                       
                       public static void main(String[] args) {
                            new RunMethod().run("C:/java/projects/myproject/classes/", "test1.MyTargetClass");
                       }
                  }
                  Compile and run the RunMethod class.

                  Hope That Helps
                  • 6. Re: running a java program using URLClassLoader
                    807606
                    Hey dude,

                    Thanks again, its been so nice of you.

                    I tried to compile your program and run it. It runs perfect but when I implement the same code in my application it does not work. May be my application tries to implement this function through an event listener(!!!???), thats why it does no work......

                    It gives me an IllegalAccessException and says that class runMethod cannot access a member of class abc with the modifier "public static"..... at sun.Reflection.ensureMemberAccess(Reflection.java: 65)
                    at java.lang.Reflect.Method.invoke(Method.java: 588 )
                    its a long list.....

                    Its quite weird why its not working....I will become mad!!!

                    Please me help out of it...I have only three days to submit my project.......
                    • 7. Re: running a java program using URLClassLoader
                      807606
                      dude,
                      I finally found out the main problem....
                      the code that you gave me runs only if the class to be run is declared public but does not run otherwise and I get the exceptions that i wrote earlier.........

                      do you know why this is happening.....
                      • 8. Re: running a java program using URLClassLoader
                        800649
                        do you know why this is happening
                        You can't access a class that's not declared as public.
                        public class means that you can access it from anywhere.

                        see Access Modifiers :http://java.sun.com/docs/books/tutorial/java/javaOO/variables.html
                        • 9. Re: running a java program using URLClassLoader
                          807606
                          hey dude,
                          thanks for the information but I most of the IDE's can run programs which do not have a 'public' main class!!!

                          do you know how do they do this???????
                          • 10. Re: running a java program using URLClassLoader
                            807606
                            here is small program compile and run it in any IDE or on the command line...
                            class Hello{
                                 public static void main(String args[]){
                                      System.out.println("Hello");
                                 }
                            }

                            and it runs.
                            How do I do that through my code????
                            • 11. Re: running a java program using URLClassLoader
                              800649
                              sorry for what I told you !!
                              I tried the example that I posted with non public class and it worked :)

                              Remove the public qualifier from the MyTargetClass and try this example again.
                              • 12. Re: running a java program using URLClassLoader
                                807606
                                Hey dude,
                                I don't know how you got that working!!!!
                                I tried the same but it gave me the same errors that i got earlier!!!!
                                as far as i have traced the exceptions, I think the problem is with 'reflections' that we are using to invoke the 'main' method

                                Maybe if we solve that problem we can get around it......
                                • 13. Re: running a java program using URLClassLoader
                                  807606
                                  Hey dude,
                                  I don't know how you got that working!!!!
                                  I tried the same but it gave me the same errors that i got earlier!!!!
                                  as far as i have traced the exceptions, I think the problem is with 'reflections' that we are using to invoke the 'main' method

                                  Maybe if we solve that problem we can get around it......
                                  • 14. Re: running a java program using URLClassLoader
                                    807606
                                    Hey dude,
                                    I don't know how you got that working!!!!
                                    I tried the same but it gave me the same errors that i got earlier!!!!
                                    as far as i have traced the exceptions, I think the problem is with 'reflections' that we are using to invoke the 'main' method

                                    Maybe if we solve that problem we can get around it......
                                    1 2 Previous Next