Re: dealing with ClassLoaders...
On Thu, 31 Jul 2014 19:40:18 +0000, Andreas Leitgeb wrote:
All the classes of my app are principially loadable by the system's
default ClassLoader (i.e. they are in the java.class.path). Some Main
class (mypackage.Main) of my app will even be loaded, and this class
will then create a new Thread with a custom ClassLoader that is supposed
to load all the other used classes of my app's packages (while still
delegating loading of newly used system classes to its parent).
The classloader tutorials I skimmed so far seem to imply, that a custom
classloader is only appropriate to enable classloading from sources that
the system classloader cannot handle itself.
This sounds similar to something I've done a couple of times now when I
wanted to put a number of related but separate programs and their
supporting classes into a jar file and then, at runtime, select the one
to be run via the command line.
The manifest Main-Class names single, top level launcher class. This is
passed the name of the program to be run plus any options and arguments
it needs via the argv[] array. The launcher class then does the following
to launch the program:
try
{
String fullAppName = PACKAGE + "." + argv[0];
MAClassLoader loader = new MAClassLoader();
Class target = loader.loadClass(fullAppName);
MAApplication app = (MAApplication)target.newInstance();
String argList[] = new String[argv.length - 1];
for (int i = 1; i < argv.length; i++)
argList[i-1] = argv[i];
app.run(argList);
}
catch (Exception e)
{
System.out.stderr.println(e.toString());
}
I've omitted the rest of main() because it only does obvious, application-
specific stuff like showing help text when requested, validating the
program name, etc. The program being run is responsible for validating
the arguments passed to it.
MAApplication is a superclass which is extended by all the programs that
can be run by the launcher. In this case they are all members of the same
package so that the user only needs to input the program name. Here is
MAClassLoader in its entirety:
package ma.internals;
/**
* MAClassLoader loads the application.
*
* The only method used from the abstract parent ClassLoader
* class is loadClass(String). As it is not abstract and
* doesn't need to be overridden, this class definition is null.
*
* Its only purpose is to convert the abstract ClassLoader
* declaration into a non-abstract class.
*/
public class MAClassLoader extends ClassLoader
{
}
I run programs with this type of command:
java -jar /usr/java/jarlib/jarfile.jar program arguments....
where 'program' is the program to be run and the arguments will be passed
to it by the launcher.
I hope this is useful info.
--
martin@ | Martin Gregorie
gregorie. | Essex, UK
org |