1

I want to run an external Java project (class) from inside a java project. I don't mean whatever program (eg. EXE files) but java classes (projects).

Let consider you have the class file path in a string:

String = "C:\\test\\test.class";
100798
  • 231
  • 6
  • 15

3 Answers3

4

This is the responsibility of the ClassLoader. If you have external .class files on disk that you want to instantiate/use, then it's relatively straightforward once you're aware of the available APIs:

File f = ...; // Folder containing the .class files

ClassLoader loader = new URLClassLoader(new URL[] { f.toURI().toURL() }, getClass().getClassLoader(););
for (File classFile : f.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.endsWith(".class");
    }
})) {
    try {
        String filename = classFile.getName();
        // Remove the .class extension
        Class<?> cls = loader.loadClass(filename.substring(0, filename.length() - 6));
        // Do something with the class
    } catch (Exception ex) {
        LOGGER.error("Unable to load plugin: " + ex.getMessage());
    }
}
Craig Otis
  • 31,257
  • 32
  • 136
  • 234
  • Your example seems to be for more general case. Consider the simplest example, where let say you have the class file path in a string String="C:\\..\\test.class". Now how to run (load) it. – 100798 Dec 11 '11 at 16:09
  • ...Did you read the code? The very first line is literally the only thing you have to write to make it work the way you want. Are there any specific pieces you are having trouble with? If you only want it to load a specific file, then you can (if you want a one-line change) alter the `FilenameFilter` to only return true for your "test.class" case. – Craig Otis Dec 11 '11 at 17:33
  • Yes, but it doesn't work. The filename keeps all the classes of the folder in the string. Even if there is one .class file it does nothing. No loading of that class. Ex. I have a simple GUI program on that folder, but it doesn't load. Even more, no error appears. – 100798 Dec 11 '11 at 18:11
  • @100798 I don't quite understand - what do you mean you have a GUI program on that folder? And what do you mean by "filename keeps all the classes of the folder in the string?" If the program isn't working and isn't spitting out errors, then you need to debug. If you have experience with breakpoints you can use those, or you can use `System.out.println()` to print out the values of your variables at certain points. We can't help you without your help. :) – Craig Otis Dec 11 '11 at 18:18
  • OK it is my fault of not explaining well the things. First, the case with GUI was just example java project which I want to run. Second, the string "filename" keeps all the .class files which are in the folder, and this I found by using Sytem.out.prinln() - example: test1.class test2.class ect. And even if I leave in the folder only one .class file as supposed, the one I want to load (run), it doesn't show anything. So, it does not load the java project. Sorry for my comments, but since I am not familiar with these things, I am confused in my comments. – 100798 Dec 11 '11 at 19:22
  • If you notice, inside the `try` block, once you have the `Class` file loaded, you still have to create an instance of that class. Again, we don't know what kind of class you have, or how to instantiate one, or what your code actually looks like, so we can only be of so much help. – Craig Otis Dec 11 '11 at 19:59
  • What do you mean by "kind of class"? The purpose of the whole topic is running of an external java project. For my case, I have the external .class file path in a string, and on click of a button (actionPerfomed function) I want to load that project. Sorry again, for my confused approach. – 100798 Dec 11 '11 at 20:31
  • A class file does not contain a project. It contains a class. (And sometimes other helper classes.) To make use of a class, you can either create an instance of that class using a constructor, or you can call static methods that the class provides. If you have static methods, you can (using the example above) call `cls.someStaticMethod()` or can create a new one: `cls.newInstance()` – Craig Otis Dec 11 '11 at 23:07
2

Besides your quite demaninding tone it seems as if you want some kind of plugin structure.

Basically, you'd need a ClassLoader that will load the classes/libaries you want. Once they are loaded you can use them.

Maybe this helps you: How to load a jar file at runtime

Community
  • 1
  • 1
Thomas
  • 87,414
  • 12
  • 119
  • 157
0

"Running" another java program is done by invoking it's main method. Say you have the class net.tilialacus.TheProg that you want to run, then you can do (in your other java program)

String[] args = {"arg1", "arg2"}; 
net.tilialacus.TheProg.main(args);

or via reflection if the class is not known at compile time:

    Class<?> theClass = Class.forName("net.tilialacus.TheProg");
    Method method = theClass.getDeclaredMethod("main", String[].class);
    String[] args = { "arg1", "arg2"};
    method.invoke(null, (Object)args);

Of course you need to handle exceptions if the class does not exist or is does not have a "public static main(String[])" method.

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
  • Lindsjo Let say I have a project example1 and its main class example1.class. How can I build and run this from my java program? Do you have any idea? – 100798 Dec 01 '11 at 10:59
  • @100798 Is the class already in the classpath? Is so you should be able to to use what I showed above. If not, then you have to load it via a class loader (see craig's answer). Which part are you having problem with? – Roger Lindsjö Dec 01 '11 at 12:14