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";
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());
}
}
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
"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.