Loading classes at runtime
I am trying to write a Java program that accepts command line arguments which
specify classes to be loaded. Can I use the functions from the Class class
to do this? The program will not know the names of the classes until it
is run, however, it will know that all of the classes that it might encounter
extend a given class. For instance, on the command line the user will type:
java MyProgram A B (where A and B are classes that both extend class Letter).
Then, MyProgram's main function will create an instance of A and an instance
Any help you can give would be greatly appreciated.
Re: Loading classes at runtime
email@example.com (Shayne) wrote in <firstname.lastname@example.org>:
>I am trying to write a Java program that accepts command line arguments
>which specify classes to be loaded. Can I use the functions from the
>Class class to do this?
See Class.forName() and Class.newInstance().
I so happens that I was just researching the exact same thing. I found a pretty helpful article that explains a lot. You may also want to check out Sun's website.
Here is the link for the article Article for loading classes during runtime. Actually they're more like a series of articles I recommend reading them all.
Last edited by Radroach; 05-12-2007 at 01:01 AM.
Reason: Adding more information
Take a look at discussion for implementing the "Strategy" design pattern - this resolves the same challenge as your question. You write your functions in your client class(es) using the method calls and data fields held in the abstract class(es) or interface(s), then have several implementing classes which provide the different look or behavior you are indicating by your command line argument(s).
Here are two concise and informative descriptions of the implementation of Strategy:
Last edited by nspils; 05-12-2007 at 08:22 AM.
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center